【问题标题】:HashMap have the key of integer[] type though its containsKey method returns false?HashMap 有 integer[] 类型的键,虽然它的 containsKey 方法返回 false?
【发布时间】:2020-01-19 17:53:57
【问题描述】:

在hackerrank上解决问题时,我发现由于逻辑错误,我的输出与正确答案不同。我重新创建了逻辑错误以更好地解释这种情况。

HashMap<Integer[] , Integer> hm = new HashMap<>();

//both a and b have different hashcode
Integer[] a = {1, 1, 0, 0};
Integer[] b = {1, 1, 0, 0}; 

hm.put(a,1);

if (!hm.containsKey(b)) {
    //key does not exists so, create new one  
    hm.put(b, 1);
}
else {
    //key does exists so, put its value = value + 1
    hm.put(b, hm.get(b)+1); 
}

这里 hm.containsKey(b) 返回 false,但如果返回 true,我的输出将匹配正确的输出。由于 a 和 b 的内容相等,如何使 containsKey(b) 返回 true?

【问题讨论】:

  • HashMap hm = new HashMap();到 HashMap , Integer> hm = new HashMap();
  • 它使用等于。但是 equals 对数组没用。
  • containsKey(key) 的文档:当且仅当此映射包含键 k 的映射使得 Objects.equals(key, k) 时才返回 true

标签: java hashmap hashcode


【解决方案1】:

您不应将数组用作HashMap 的键,因为数组不会覆盖equalshashCode,因此包含完全相同元素的不同数组实例不会被@ 视为相同987654324@.

改用List&lt;Integer&gt; 键。

Map<List<Integer>, Integer> hm = new HashMap<>();

List<Integer> a = List.of(1, 1, 0, 0);
List<Integer> b = List.of(1, 1, 0, 0);

hm.put(a,1);

if (!hm.containsKey(b)) {
    //key does not exists so, create new one  
    hm.put(b, 1);
}
else {
    //key does exists so, put its value = value + 1
    hm.put(b, hm.get(b)+1); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2016-05-13
    • 2012-10-04
    相关资源
    最近更新 更多