I am trying to override equals method in Java. I have a class People
which basically has 2 data fields name
and age
. Now I want to ove
I'm not sure of the details as you haven't posted the whole code, but:
hashCode()
as wellequals
method should have Object
, not People
as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.instanceof
to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
equals
is used for all objects, but not primitives. I think you mean age is an int
(primitive), in which case just use ==
. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.See What issues should be considered when overriding equals and hashCode in Java? for more details.