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

问题描述

我有一个名为 Person 的类.它具有以下属性;它有 2 个属性,IDTelephone.一个人可以有多个电话,所以你可能会在下面看到有多个ID的人.

I have a class called Person. It has the following attributes; It has 2 attributes, ID, and Telephone. 1 person can have many telephones, so you may see people with multiple ID's below.

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 phone) 的方法.

There's another class called PersonDB. and it will have a method called, 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 对象匹配的对象.我怎样才能做到这一点?

The personList, has 3-4 Person objects. I need to search the PersonArrayList and find the object that will match the Person object. How can i get this done ?

注意:我试过personList.contains().但这不起作用.

Note: i tried personList.contains(). But this doesn't work.

推荐答案

确保您覆盖了 Person 类的 Object.equals()Object.hashCode().但是假设电话号码是唯一的,您必须对电话号码进行平等检查.这不是解决方案,而是解决方法.使用 bellum 的答案.将其标记为正确答案.

Make sure you override Object.equals() and Object.hashCode() for Person class. But you have to have equality check on telephone number assuming telephone number unique. This would not be a solution but a workaround. Use bellum's answer. Mark it as correct answer.

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

10-11 13:07