2016-01-20 76 views

回答

1

不可能。 HashMap(密钥始终是唯一的)

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

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

Ex。

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 
} 
+0

有没有办法打印错误消息让用户知道他们不能创建另一个键? – fs2ly

+0

您可以使用该功能扩展HashMap – rbp

-1

钥匙始终处于一个HashMap独特的,但是当你在你的填充HashMap中,你可以做用的containsKey(对象键)支票的HashMap的方法,如果返回true,则打印错误。所以它可能看起来像这样:

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