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

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

问题描述

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

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

推荐答案

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

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

话虽如此,有更好的方法来执行此搜索.就我个人而言,如果我使用的是 ArrayList,我的解决方案将类似于 Jon Skeet 发布的解决方案.

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天全站免登陆