0

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"; 
    }
}
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • 2
    In addition to overriding hashCode, also fix the implementation of equals(). It's not supposed to throw an exception if you pass an instance of another class, or null. It must return false in these cases. – JB Nizet Jul 05 '14 at 08:52

2 Answers2

7

You also have to override the method hashCode.

@Override
public int hashCode() {
    return toString().hashCode(); 
}
nosid
  • 48,932
  • 13
  • 112
  • 139
1

Remember to override hashCode whenever you override equals.

Henry
  • 42,982
  • 7
  • 68
  • 84