【问题标题】:How to print an error message if two keys are the same in a HashMap? (JAVA)如果 HashMap 中的两个键相同,如何打印错误消息? (JAVA)
【发布时间】:2016-01-20 18:46:11
【问题描述】:

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

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

【问题讨论】:

    标签: java oop error-handling hashmap key


    【解决方案1】:

    不可能。 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
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2013-07-25
      • 2021-03-03
      • 1970-01-01
      • 2018-08-08
      相关资源
      最近更新 更多