首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在java ArrayList中搜索

在java ArrayList中搜索
EN

Stack Overflow用户
提问于 2009-06-12 06:12:30
回答 7查看 165.7K关注 0票数 17

我正在尝试找出在ArrayList中通过Id号搜索客户的最佳方法。下面的代码不起作用;编译器告诉我缺少一条return语句。

代码语言:javascript
复制
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;
}
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-06-12 06:18:03

编译器正在抱怨,因为您当前在for循环中有'if(exist)‘块。它需要在它之外。

代码语言:javascript
复制
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发布的解决方案类似。

票数 18
EN

Stack Overflow用户

发布于 2009-06-12 09:06:48

就我个人而言,我现在很少自己编写循环,当我可以逃脱惩罚的时候……我使用Jakarta commons库:

代码语言:javascript
复制
Customer findCustomerByid(final int id){
    return (Customer) CollectionUtils.find(customers, new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((Customer) arg0).getId()==id;
        }
    });
}

耶!我只保留了一行!

票数 16
EN

Stack Overflow用户

发布于 2009-06-12 06:18:30

代码语言:javascript
复制
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
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/985229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档