Having Node abstract class which Cell extends him .
In Cell I implemented public boolean equals(Node cmpCell) . I created Set<Node> closeList = new HashSet<Node>(); and when I execute closeList.contains((Cell) node) I debugged it and detect that it utterly ignores Cell equals I implemented . What I did wrong ?
Edit :
I changed in Cell to
@Override
public boolean equals(Object cmpCell)
and still closeList.contains((Cell) node) doesn’t using the above override .
2nd Edit :
In Cell class there is 2 members –
int colIndex ;
int rowIndex ;
the equals override just compare them to that both members of the 2nd class , I think it would be better I use HashMap<K, V> but still I would be glade to know how the hashCode should be looks like in such case ?
This is not a valid override. The syntax of
equalsmethod ofObjectclass is: –And yes, as pointed out by @JonSkeet in comment, whenever you are overriding
equalsmethod, also remember to overridehashCodemethod to follow the contract ofequalsandhashCode. Because if you don’t do that, then even if yourequalsmethod shows evaluates your instances as equal, the defaulthashCodeimplementation inObjectclass will generatedifferent hashCodesfor them, and hence they won’t be equal.Also, ensure that, while calculating
hashcode, you consider only those attributes, that you used to compare your instances inequalsmethod. Else, again you will get incorrect result.In addition to that, if you are using any IDE like Eclipse, it generates a very nicely overridden and compatible
equalsandhashCodemethod for you. You should be better using them.You need to
right-clickon your class, go tosourceand selectGenerate equals and hashCode method.