从 Arraylist 返回对象 [英] Return Objects from Arraylist
问题描述
我的问题是,我想从 ArrayList
块"返回一个对象.我的代码不起作用 - 错误提示 This method must return a result of type block
My problem is, that I want to return an Object from the ArrayList
"blocks".
My code doesn't work - error says This method must return a result of type block
public block getBlockUnderneath (int x, int y){
for(int i = 0; i<blocks.size(); i++){
if (blocks.get(i).x == x) {
return blocks.get(i);
}
}
}
推荐答案
你有两个问题:
- 如果
blocks.size()==0
你的方法什么都不返回 - 如果
blocks
中的块都没有block.x==x
,则您的方法不返回任何内容.
- If
blocks.size()==0
your method returns nothing - If none of the blocks in
blocks
haveblock.x==x
your method returns nothing.
在 Java 中,方法必须返回它的值,声明这样做.
In Java a method must return a value of it is declared to do so.
解决您问题的最简单方法是在方法末尾return null
:
The easiest solution to your issue is to return null
at the end of the method:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
return null;
}
请注意,这使用了增强的 for 循环,这是在 Java 中循环Collections
(或任何实现 Iterable
)的推荐方法.
Notice this uses an enhanced-for-loop, this is the recommended way to loop over Collections
(or anything that implements Iterable<T>
) in Java.
更好的方法可能是在未找到任何项目时抛出异常:
A better approach might be to throw an exception if no item is found:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
throw new NoSuchElementException();
}
无论哪种情况,您都需要在调用此方法的代码中处理极端情况.
In either case you would need to handle the corner case in code that calls this method.
附言请遵守 Java 命名约定.类应该在 PascalCase
中 - 所以你的 block
类应该被称为 Block
.
P.S. please stick to Java naming conventions. Classes should be in PascalCase
- so you block
class should be called Block
.
只是为了好玩,在 Java 8 中:
Just for fun, in Java 8:
public block getBlockUnderneath(int x, int y) {
return blocks.stream().filter((b) -> b.x == x).findFirst().get();
}
这篇关于从 Arraylist 返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!