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 override equals
method so that I can check between 2 People objects.
My code is as follows
public boolean equals(People other){
boolean result;
if((other == null) || (getClass() != other.getClass())){
result = false;
} // end if
else{
People otherPeople = (People)other;
result = name.equals(other.name) && age.equals(other.age);
} // end else
return result;
} // end equals
But when I write age.equals(other.age)
it gives me error as equals method can only compare String and age is Integer.
Solution
I used ==
operator as suggested and my problem is solved.
I'm not sure of the details as you haven't posted the whole code, but:
hashCode()
as wellequals
method should haveObject
, notPeople
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 anint
(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.
The method equals defines a method parameter of type Object and its return type is boolean.
when you define (override) this method in your class to compare two objects.
When comparing objects in Java, you make a semantic check, comparing the type and identifying state of the objects to:
null
Rules:
a.equals(b) == b.equals(a)
equals()
always yieldstrue
orfalse
, but never aNullpointerException
,ClassCastException
or any other throwableComparison:
instanceof
for type comparison (which only works as long as there are no subclasses, and violates the symmetry rule whenA extends B -> a instanceof b != b instanceof a)
.For your
Person
class:Reusable, generic utility class:
For your
Person
class, using this utility class: