程序将根据 If 语句打印不正确的键和值。有人可以解释为什么吗?
例如 Key = Uncle tom + Value = 02086542222 Key = Harry + Value = 020826262
查询 = 汤姆叔叔
返回 = 键 = 哈利 + 值 = 00826262
从以下文档中引用:
“更正式地说,当且仅当此映射包含键 k 的映射时才返回 true 使得 (key==null ? k==null : key.equals(k))”
所以我的印象是if(Contacts.containsKey(query))会使用key.equals(k)将输入查询与键进行比较
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class HRHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
Map<String, Integer> Contacts = new HashMap<String, Integer>();//Specify HashMap of type String
int numOfContacts = scan.nextInt();
scan.nextLine();
//Add contacts
for (int i = 0; i < numOfContacts; i++) {
String contactName = scan.nextLine();
int contactNumber = scan.nextInt();
scan.nextLine();
Contacts.put(contactName, contactNumber);
}
//Iterate over the Map
for (Entry<String, Integer> entry : Contacts.entrySet()) {
String query = scan.nextLine();
if (Contacts.containsKey(query)) {
//System.out.println(Contacts.get(query));
System.out.println(entry.getKey() + "=" + entry.getValue());
} else {
System.out.println("Not found");
}
}
}
}