我正在尝试创建一个在 Java 中使用 HashMap
的 PhoneBook
类。当我在 addContact()
中使用 put()
方法添加条目时,它工作正常,但是当我尝试检索 searchContact()< 中的值时
方法,没有返回。我没有得到空值; HashMap
肯定包含我正在搜索的键,但与该键关联的值不会被返回。预先感谢您。
这是我的代码:
public class PhoneBookContactsImpl {
private Map<String, List<String>> contactMap = new HashMap<String, List<String>>();
public void addContact(String name, List<String> list) {
contactMap.put(name, list);
//its working fine here
System.out.println(contactMap.get(name));
}
public Map<String, List<String>> getContactMap() {
Set set = contactMap.entrySet();
Iterator i = contactMap.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : ");
List<String> nos = (List<String>) me.getValue();
System.out.println("Nos = " + nos + " n ");
System.out.println(nos.size());
}
return contactMap;
}
public List<String> searchContact(String name) throws NoDataFoundException {
if (contactMap.isEmpty()) {
System.out.println("Empty PhoneBook");
throw new NoDataFoundException();
} else {
if (contactMap.containsValue(name))
return contactMap.get(name);
//it doesnt retrieve valur from here
else {
System.out.println("No Entry for Specified Entry");
throw new NoDataFoundException();
}
}
}
}
最佳答案
您的 if 语句正在检查电话簿是否具有 name
作为值,因此您的 get 永远不会到达。
试试这个:
if (contactMap.containsKey(name))
return contactMap.get(name);
关于Java HashMap,get(key)方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24067159/