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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…