vert.x
vert.x copied to clipboard
JsonObject.hashCode() and JsonArray.hashCode() do not conform to contract
Version
Vert.x 4.0.3
Steps to reproduce
The implementation of hashCode() in JsonObject
and JsonArray
just returns the underlying list or map's hashCode()
value. However, the corresponding equals()
function in each class doesn't just return the underlying list or map's equals()
value. Instead, a custom implementation is used. Specifically, numerical values have special handling in the equals()
function in order to allow, e.g., Float
and Integer
objects to compare as equal if their underlying primitive values are equal. CharSequence
objects are also have special handling.
This means that two objects could compare equal via equals()
but return different hashCode()
values. This violates the Java contract for equals()
and hashCode()
. This can be an issue when storing JsonObject
and JsonArray
objects in a HashSet
or HashMap
collection, since these collections assume that objects with different hashCode()
values are not equal.
The recommended solution is to create a custom hashCode()
implementation in both JsonObject
and JsonArray
that mimics the equals()
implementation and so returns the same hashCode()
value for any two objects if equals()
returns true when called on those two objects.
FYI, #2026 was a similar issue except that it already had a custom hashCode() implementation and so was easier to fix.