有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在ArrayList中搜索特定对象

我有一个叫做Person的类。它有以下attributes;它有两个属性:IDTelephone。一个人可以有很多电话,所以你可能会看到下面有多个ID的人

public ArrayList<Person> all(){

    p = new ArrayList<Person>();
    p.add(new Person(1,266763));
    p.add(new Person(1, 358643));
    p.add(new Person(2, 4667763));

    return p; 
}

还有一个叫做PersonDB的类。它将有一个名为findPersonWithTheTelephoneNumber(int telephone)的方法

public void findPersonWithTheTelephoneNumber(int telephone) {
   Person pp = new Person();
   ArrayList<Person> personList = pp.all();

   // Now i want to find the Person object that will match the telephone number of these list of personList.


}

personList有3-4个Person对象。我需要搜索PersonArrayList并找到与Person对象匹配的对象。我该怎么做

注意:我试过personList.contains()。但这不管用


共 (2) 个答案

  1. # 1 楼答案

    //...
    Person foundPerson = null;
    for (Person p : personList){
        if (p.getTelephone() == telephone){
             foundPerson = p; //or simply return it from there
             break;
        }
    }
    

    为了实现hashCodeequals,您可以观察this tutorial

  2. # 2 楼答案

    在许多解决方案中,通过电话号码将两个人定义为相等,但如果两个住在同一栋房子和/或拥有相同电话号码的人被添加到列表中呢?哪一个是正确的

    在匆忙寻找那个人之前,你必须确定一种方法,以确定两个人是否真的是平等的,而不会产生模棱两可的结果。除非您通过使该电话号码唯一来限制基于该电话号码创建人员(您没有在问题中阐明这一点,因此我假设没有此类限制),否则搜索结果是未定义的

    您使用的是ArrayList,因此无法通过插入顺序保证结果

    我建议你把平等测试的基础放在一个人的ID而不是他的手机上。为了防止修改id,只需为它定义一个getter,而完全不定义setId方法。然后,您可以基于id重新定义equals(和hashcode,如果您愿意的话)