I have a arrayList and i want use contains(Thing o) method to check equality of this two object and I override the equals() method in Thing class but this is not work when I call contains method! this is my thing class:
public class Thing{
private int id;
//getter setter
@Override
public boolean equals(Object o) {
if(!(o instanceof Thing))
return false;
if(id == ((Thing)o).getId())
return true;
return false;
}
}
is it necessary to override the hashCode() method too? if yes how to override it?
You should override hashCode. The ArrayList class doesn't use the hashCode method so it's not necessary now, but if at any point you are going to use your class with HashMap, HashSet, or any other collection that does use hashCode, the program will break because hashCode and equals are not consistent.
A simple implementation of hashCode for this case could be:
public int hashCode() {
return id;
}
Yes, it is essential to override hashCode() whenever u override equals :
If you do not overrode HashCode(), the default behaviour from the "Object" class is to give each object a unique hashCode.
This unique hashCode would mean two different object instances unless
you override the hashCode() to give the same value.
public int hashCode(){ return this.id; }
you dont have to write this manually when you are using Eclipse.:) RightCLick on the java file opened -->Source-->Generate HashCode() and equals()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With