我正在尝试找出在ArrayList
中通过Id号搜索客户的最佳方法。下面的代码不起作用;编译器告诉我缺少一条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;
}
发布于 2009-06-12 06:18:03
编译器正在抱怨,因为您当前在for循环中有'if(exist)‘块。它需要在它之外。
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);
}
也就是说,有更好的方法来执行此搜索。就我个人而言,如果我使用的是ArrayList,我的解决方案将与Jon Skeet发布的解决方案类似。
发布于 2009-06-12 09:06:48
就我个人而言,我现在很少自己编写循环,当我可以逃脱惩罚的时候……我使用Jakarta commons库:
Customer findCustomerByid(final int id){
return (Customer) CollectionUtils.find(customers, new Predicate() {
public boolean evaluate(Object arg0) {
return ((Customer) arg0).getId()==id;
}
});
}
耶!我只保留了一行!
发布于 2009-06-12 06:18:30
Customer findCustomerByid(int id){
for (int i=0; i<this.customers.size(); i++) {
Customer customer = this.customers.get(i);
if (customer.getId() == id){
return customer;
}
}
return null; // no Customer found with this ID; maybe throw an exception
}
https://stackoverflow.com/questions/985229
复制相似问题