2 HashMap 之间的相等性 [英] Equality between 2 HashMap

查看:25
本文介绍了2 HashMap 之间的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In the equals() method of my class, I am using a private instance HashMap variable to compare for the equality. However, 2 different objects still show being equal when comparing their HashMap variables. Further research brought me to the link : Link Here . However, it just says that the reason for HashMap1.equals(HashMap2) not working is because " apparantly Java's arrays cannot be tested for equality without writing a customized code."

I did not understand this reason. Can anyone please guide me to a elaborate reason?

解决方案

The equals method on a Java array type is equivalent to ==, because Java array "classes" do not override Object.equals.

If you want to compare arrays "by value" you need to either use the appropriate java.util.Arrays.equals(...) method, or implement it yourself.

If your HashMap uses arrays as keys or values, then it is going to call the array's equals method to test if the keys and/or values are the same between two maps. This would make HashMap.equals behave strangely (from your perspective). That is what the linked article is saying. However, array semantic only affect HashMap equality if you use arrays as the key or value classes. If you don't, then HashMap::equals should just work as expected.

The javadocs for equality on Map classes are a bit involved, but they basically boil down to taking the two entry sets, comparing their sizes, and then doing s1.containsAll(s2). Of course, this is expensive, but it should work for all of the Map classes that correctly implement the Map interface.


Note that using arrays as keys for maps is a bad idea for a couple of reasons:

  1. The semantics of array equals and hashCode are wrong for a HashMap in most scenarios. For most use-cases, you need the map to compare the keys by value not by object identity.
  2. Arrays are mutable. If we assumed that there was a workaround for the equals / hashcode problem, you could still break a map's invariants by modifying an array key.

这篇关于2 HashMap 之间的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆