gpt4 book ai didi

Java HashMap,get(key)方法不起作用

转载 作者:行者123 更新时间:2023-11-30 07:08:20 25 4
gpt4 key购买 nike

我正在尝试创建一个使用 Java 中的 HashMapPhoneBook 类。当我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com