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?
Map. equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.
If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap. keySet() function. It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set.
HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.
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:
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.equals
/ hashcode
problem, you could still break a map's invariants by modifying an array key. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With