Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

java - Equality between 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...