在java中ArrayList中搜索 [英] search in java ArrayList

查看:108
本文介绍了在java中ArrayList中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出它的ID号来搜索在的ArrayList 客户的最佳途径。下面的code不工作;编译器告诉我,我缺少一个收益语句。

 客户findCustomerByid(INT ID){
    布尔存在= FALSE;    如果(this.customers.isEmpty()){
        返回null;
    }    的for(int i = 0; I< this.customers.size();我++){
        如果(this.customers.get(ⅰ).getId()== id)的{
            存在= TRUE;
            打破;
        }        如果(存在){
            返回this.customers.get(ID);
        }其他{
            返回this.customers.get(ID);
        }
    }}// Customer类是类似的东西
公共类客户{
    //属性
    INT ID;
    INT联系电话;
    串FNAME;
    字符串LNAME;
    串resgistrationDate;
}


解决方案

编译器是抱怨,因为您目前内部的for循环如果(存在)'块。它需要外界的吧。

 的for(int i = 0; I< this.customers.size();我++){
        如果(this.customers.get(ⅰ).getId()== id)的{
            存在= TRUE;
            打破;
        }
}如果(存在){
    返回this.customers.get(ID);
}其他{
    返回this.customers.get(ID);
}

话虽这么说,有更好的方法来执行此搜索。就个人而言,如果我用一个ArrayList,我的解决方案将看起来像乔恩斯基特已发布一。

I'm trying to figure out the best way to search a customer in an ArrayList by its Id number. The code below is not working; the compiler tells me that I am missing a return statement.

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

解决方案

The compiler is complaining because you currently have the 'if(exist)' block inside of your for loop. It needs to be outside of it.

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

That being said, there are better ways to perform this search. Personally, if I were using an ArrayList, my solution would look like the one that Jon Skeet has posted.

这篇关于在java中ArrayList中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆