如果 HashMap 中的两个键相同,如何打印错误消息? (JAVA)

How to print an error message if two keys are the same in a HashMap? (JAVA)

如果 HashMap 中的两个键相同,如何打印错误消息? (JAVA)

我希望哈希图中的每个键都是唯一的;我该怎么做?

不可能。 HashMap(键总是唯一的)

如果您将相同的键放入 HashMap 中,它将覆盖您已插入的旧键和值。

如果要打印错误消息,则必须在插入之前在外部完成密钥检查。

例如

Iterator it = hashmap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry keys = (Map.Entry)it.next();
    if(keys.getKey().equals(your_user_input)) {
             //throw exception, logs, or print your error msg.
     }
    it.remove(); //ConcurrentModificationException 
}

键在 HashMap 中始终是唯一的,但是当您填充 HashMap 时,您可以使用 HashMap 的 containsKey(Object key) 方法进行检查,如果 returns 为真,则打印您的错误。所以它可能看起来像这样:

if(yourMap.containsKey(yourKey)){
   //print you error
}else{
   yourMap.put(yourKey,yourValue);
}