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

时间:2016-01-20 18:46:11

标签: java oop error-handling hashmap key

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

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

2 个答案:

答案 0 :(得分:1)

不可能。 HashMap(键总是UNIQUE)

如果在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 
}

答案 1 :(得分:-1)

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

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