搜索一个ArrayList特定对象 [英] Search an ArrayList for a particular Object
问题描述
我有一个名为人
类。它具有以下属性
;它有2个属性, ID
和电话
。 1人可以有很多电话,所以你可能会看到多个ID的人之下。
公开的ArrayList<&人GT;所有(){ P =新的ArrayList<&人GT;();
p.add(新的Person(1,266763));
p.add(新的Person(1 358643));
p.add(新的Person(2 4667763)); 回磷;
}
有被称为另一个类 PersonDB
。它将呼吁的方法, findPersonWithTheTelephoneNumber(INT电话)
。
公共无效findPersonWithTheTelephoneNumber(INT电话){
人PP =新的Person();
ArrayList的<&人GT; personList = pp.all(); //现在我想找到Person对象,将personList这些列表的电话号码一致。
}
该personList,有3-4个Person对象。我需要搜索PersonArrayList,发现将匹配Person对象的对象。如何才能得到这个工作?
请注意:我试图 personList.contains()
。但是,这是行不通的。
我试过personList.contains()
块引用>请确保您覆盖
是Object.equals()
和Object.hash code()
的人类。但是你必须对假设的电话号码唯一的电话号码平等检查。这不会是一个解决方案,但一种变通方法。使用战争权的回答。将其标记为正确答案。I have a class called
Person
. It has the followingattributes
; It has 2 attributes,ID
, andTelephone
. 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; }
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. }
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 ?
Note: i tried
personList.contains()
. But this doesn't work.解决方案i tried personList.contains()
Make sure you override
Object.equals()
andObject.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特定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!