Deserialization of JavaScript array to Java LinkedHashSet using Jackson and Spring doesn't remove duplicates

Only overriding equals method will not work because hash-based collections use both the equals and hashCode method to see if two objects are the same. You'll need to override hashCode() method in Entity class as both hashCode() and equals() method are required to be properly implemented to work with Hash based collections.

If your requirement is that if the some or all of the fields of two objects of the Entity class are same, then the two objects are to be considered equivalent, in that case, you'll have to override both equals() and hashCode() method.

For e.g. - if only id field in the Entity class is required to determine if the two objects are equal, then you'll override equals(), something like this:

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o instanceof Entity){
        Entity that = (Entity) o;
        return this.id == null ? that.id == null : this.id.equals(that.id);
    }
    return false;

}

but along with it, the hashCode() method need to be overridden in a way to produce same hashcode if id has the same value, maybe something like this:

@Override
public int hashCode() {
    int h = 17;
    h = h * 31 + id == null ? 0 : id.hashCode();
    return h;
}

Only now it'll work properly with Hash based collections, as both these methods are used to identify an object uniquely.


More on this:

  • Relationship between hashCode and equals method in Java
  • Why do I need to override the equals and hashCode methods in Java?

Assuming that if the members of Entity class i.e. the id and type are same then the object of class Entity is same is completely wrong unless and until you override the hashcode() and equals() function explicitly.

If you do not override the hashCode() and equals() function in your Entity class then the two objects will be different even though they have same data within their members.


In Java, objects equality is determined by overriding the equals() and hashcode() contract.

There are default implementations of equals() and hashCode() in Object. If you don't provide your own implementation, those will be used. For equals(), this means an == comparison: the objects will only be equal if they are exactly the same object.

Answer to your question : Objects in LinkedHashSet are inheriting default behaviour of equals() and hashcode() methods from Object class. Override equals() and hashcode() of Entity class of LinkedHashSet

See below this for default behaviour of hashcode() and equals().