在java ArrayList中搜索

我正在尝试找出通过其ID号在ArrayList搜索客户的最佳方法。 以下代码无效; 编译器告诉我,我错过了一个return语句。

 Customer findCustomerByid(int id){ boolean exist=false; if(this.customers.isEmpty()) { return null; } for(int i=0;i<this.customers.size();i++) { if(this.customers.get(i).getId() == id) { exist=true; break; } if(exist) { return this.customers.get(id); } else { return this.customers.get(id); } } } //the customer class is something like that public class Customer { //attributes int id; int tel; String fname; String lname; String resgistrationDate; } 

编译器抱怨,因为你的for循环中当前有’if(exists)’块。 它需要在它之外。

 for(int i=0;i 

话虽如此,有更好的方法来执行此搜索。 就个人而言,如果我使用的是ArrayList,我的解决方案看起来就像Jon Skeet发布的那个。

其他人已经指出了现有代码中的错误,但我想进一步采取两个步骤。 首先,假设您使用的是Java 1.5+,您可以使用增强的for循环实现更高的可读性:

 Customer findCustomerByid(int id){ for (Customer customer : customers) { if (customer.getId() == id) { return customer; } } return null; } 

这也消除了在循环之前返回null的微优化 – 我怀疑你会从中获得任何好处,而且代码更多。 同样我删除了exists标志:一旦你知道答案使代码更简单就返回。

请注意,在您的原始代码中,我认为您有一个错误。 在发现索引i处的客户拥有正确的ID之后,您又以索引id返回了客户 – 我怀疑这是否是您的意图。

其次,如果您要通过ID进行大量查找,您是否考虑过将您的客户放入Map

就个人而言,我现在很少自己写循环,当我可以逃脱它…我使用雅加达公共库:

 Customer findCustomerByid(final int id){ return (Customer) CollectionUtils.find(customers, new Predicate() { public boolean evaluate(Object arg0) { return ((Customer) arg0).getId()==id; } }); } 

好极了! 我保存了一行!

 Customer findCustomerByid(int id){ for (int i=0; i 

你错过了return语句,因为如果你的列表大小为0,for循环将永远不会执行,因此if将永远不会运行,因此你永远不会返回。

将if语句移出循环。

即使这个话题很老,我也想补充一些东西。 如果你为你的类覆盖了equals ,那么它比较你的getId ,你可以使用:

 customer = new Customer(id); customers.get(customers.indexOf(customer)); 

当然,您必须检查IndexOutOfBounds -Exception,它会被转换为空指针或自定义CustomerNotFoundException

在Java 8中:

 Customer findCustomerByid(int id) { return this.customers.stream() .filter(customer -> customer.getId().equals(id)) .findFirst().get(); } 

将返回类型更改为Optional也可能更好。

我做了一些接近的事情,编译器看到你的return语句在If()语句中。 如果要解决此错误,只需在If语句之前创建一个名为customerId的新局部变量,然后在if语句中指定一个值。 在if语句之后,调用return语句,并返回cstomerId。 喜欢这个:

 Customer findCustomerByid(int id) { boolean exist=false; if(this.customers.isEmpty()) { return null; } for(int i=0;i