org.vertx.java.core.json.JsonObject equals() and hashCode()

195 views
Skip to first unread message

Randy Tidd

unread,
Jul 25, 2014, 3:10:23 PM7/25/14
to ve...@googlegroups.com
vert.x's JsonObject implements equals() but not hashCode(), the result is that two different objects with the same values are equal but won't hash the same:

        JsonObject json1 = new JsonObject().putString("foo","bar");
       
JsonObject json2 = new JsonObject().putString("foo","bar");

        logger
.info("equals = " + Boolean.toString(json1.equals(json2)));

this returns true, while this

        Set<JsonObject> set = new HashSet<>();
       
set.add(json1);
        logger
.info("contains json1 = " + Boolean.toString(set.contains(json1)));
        logger
.info("contains json2 = " + Boolean.toString(set.contains(json2)));

returns true for the first log statement and false for the second.

I ran into this because I was using Map and Set to keep an in-memory collection of JsonObjects and noticed the hashing behavior.

This is in contrast to for example Google's gson toolkit, this:

        com.google.gson.JsonObject gson1 = new com.google.gson.JsonObject();
        gson1
.addProperty("foo", "bar");
        com
.google.gson.JsonObject gson2 = new com.google.gson.JsonObject();
        gson2
.addProperty("foo", "bar");

        logger
.info("equals = " + Boolean.toString(gson1.equals(gson2)));

       
Set<com.google.gson.JsonObject> set2 = new HashSet<>();
        set2
.add(gson1);
        logger
.info("contains gson1 = " + Boolean.toString(set2.contains(gson1)));
        logger
.info("contains gson2 = " + Boolean.toString(set2.contains(gson2)));

returns true for all log statements.

This isn't to suggest that Google's JSON implementation is better or that vert.x's is wrong, I think the "best" or "correct" behavior here is certainly debatable.

But my question is if this is intentional, is there some vert.x internal reason why JsonObject shouldn't hash, or if this would be considered a defect?  The workaround is to just hash on the object's toString() value which is easy enough.

Randy
Reply all
Reply to author
Forward
0 new messages