我將一個聯繫人列表存儲爲類型爲「Person」的HashMap,並希望具有搜索功能,以便我可以搜索HashMap並返回名爲「John」的所有人以及例如,住在美國的人。我的想法是隻要創建人與環的ArrayList通過增加每個值作爲例如:在多個值中搜索一個HashMap
Map<Person, Person> hm = new HashMap<Person, Person>();
ArrayList<String> result = new ArrayList<String>();
Enumeration num= hm.keys();
String name = "John";
String location = "USA";
while (num.hasMoreElements()) {
Person person = (Person) num.nextElement();
if(person.name.equals(name) && person.location.equals(location))
{
result.add(person);
}
我只是想知道這是否會工作正確的,或者如果有,我已經忽略了這樣的一些更好的方法。
感謝
您正在使用'Map',但看起來您確實應該使用'Set '。您可以閱讀更多:http://java67.blogspot.com.au/2013/01/difference-between-set-list-and-map-in-java.html –