从Arraylist返回对象

从Arraylist返回对象

本文介绍了从Arraylist返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,我想从 ArrayList "blocks"返回一个对象.我的代码不起作用-错误提示此方法必须返回类型为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);
         }
    }
}

推荐答案

您有两个问题:

  1. 如果 blocks.size()== 0 ,则您的方法不返回任何内容
  2. 如果 block 中的所有块都没有 block.x == x ,则您的方法不返回任何内容.
  1. If blocks.size()==0 your method returns nothing
  2. If none of the blocks in blocks have block.x==x your method returns nothing.

在Java中,方法必须返回其声明的值.

In Java a method must return a value of it is declared to do so.

最简单的解决方法是在方法末尾返回空:

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;
}

请注意,此方法使用了增强的循环功能,这是在Java中循环遍历 Collections (或任何实现Iterable< T> 的内容)的推荐方法.

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.

P.S.请遵守 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返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:11