fen*_*nec 17 java search arraylist
我正试图找出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;
}
Jon*_*eet 55
其他人已经指出了现有代码中的错误,但我想进一步采取两个步骤.首先,假设您使用的是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<Integer, Customer>?
Bra*_*lor 17
编译器抱怨,因为你的for循环中当前有'if(exists)'块.它需要在它之外.
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发布的解决方案.
Dan*_*ell 16
就个人而言,我现在很少自己写循环当我可以逃脱它...我使用Jakarta commons libs:
Customer findCustomerByid(final int id){
    return (Customer) CollectionUtils.find(customers, new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((Customer) arg0).getId()==id;
        }
    });
}
好极了!我保存了一行!
Luc*_*ero 11
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
}
| 归档时间: | 
 | 
| 查看次数: | 155494 次 | 
| 最近记录: |