Search code examples
javacollectionssetduplicateslinkedhashset

LinkedHashSet is not Removing Duplicates


I am using LinkedHashSet for removing duplicated entries. But for below custom model the Set still keeps duplicate entries. Please help me to find the bugs. Is there anything wrong with overriding equals method. For your kind information i only treats two node equals when their phone, type and status are same.

public class BlockNode { 
    public int id;
    public int type;
    public int status;
    public String phone;
    public String date;
    public String content;

    @Override
    public boolean equals(Object o) {
        return this.toString().equals(((BlockNode)o).toString());
    }

    @Override
    public String toString() {
        return "number:" + phone + " type:" + type + " status:" + status + "\n"; 
    }
}

Solution

  • You also have to override the method hashCode.

    @Override
    public int hashCode() {
        return toString().hashCode(); 
    }