即使与另一个具有相同值的HashMap进行比较,HashMap values()。equals()始终返回false

时间:2019-04-08 12:24:18

标签: java hashmap

我试图通过使用hashMap.values()。equals()来检查两个哈希图的值是否相等。但是,即使两个HashMap具有相同的值,也不会视为相等。

String s = "egg";
String t = "add";
int count = 0;
HashMap<String,Integer> hashMap = new HashMap<>();

for (int i = 0; i < s.length(); i++) {
    String val = String.valueOf(s.charAt(i));

    if (!hashMap.containsKey(val)) {
        count++;
        hashMap.put(val, count);
    } else {
        hashMap.put(val, hashMap.get(val));
    }
}

HashMap<String,Integer> hashMap2 = new HashMap<>();
int count2 = 0;
for (int j = 0; j < t.length(); j++) {
    String val = String.valueOf(t.charAt(j));

    if (!hashMap2.containsKey(val)) {
        count2++;
        hashMap2.put(val, count2);
    } else{
        hashMap2.put(val, hashMap2.get(val));
    }
}

if (hashMap.values().equals(hashMap2.values())) {
    return true;
} else {
    return false;
}

2 个答案:

答案 0 :(得分:2)

您正在比较两个集合,它们将永远不相等,因为您正在对两个不同的集合进行参考比较。 Apache commons-collections具有CollectionUtils#isEqualCollection,请使用它。当然,如果您要创建自己的类作为地图的值,请在其中实现equals和hashCode。

答案 1 :(得分:2)

Since hashMap.values() is return Collection<T> we cannot compare it with equals(). Thanks to Ali Ben Zarrouk for help. Here is the implementation of how to check if values of two hashmaps are equal or not without using any third party library.

   if(areHashMapValuesEqual(hashMap.values(),hashMap2.values())){
        return true;
    } else {
        return false;
    }

  static <T> boolean areHashMapValuesEqual(Collection<T> lhs, Collection<T> rhs) {
    boolean equals = false;
    if(lhs!=null && rhs!=null) {
        equals = lhs.size( ) == rhs.size( ) && lhs.containsAll(rhs)  && rhs.containsAll(lhs);
    } else if (lhs==null && rhs==null) {
        equals = true;
    }
    return equals;
}