How do I override the equals method in the object class?
i.e I have
class Person{
//need to override here
public boolean equals (Object obj){
}
I want to convert the parameter obj to a type Person, but if I do (Person) obj it won't work.
How do I override the equals method in the object class?
i.e I have
class Person{
//need to override here
public boolean equals (Object obj){
}
I want to convert the parameter obj to a type Person, but if I do (Person) obj it won't work.
You can cast it inside the method, just make sure that is of the right type using instance of
if(obj instanceof Person)
{
Person otherPerson = (Person) obj;
//Rest of the code to check equality
}
else
{
//return false maybe
}
It's actually more complicated than you might think. Have Eclipse (or whatever IDE you're using) auto-generate an equals
method; you'll see it contains a few checks and casts before it does a comparison.
Also see here: http://www.javapractices.com/topic/TopicAction.do?Id=17
@Override
public boolean equals(Object o)
{
if (o instanceof Person)
{
Person c = (Person) o;
if ( this.FIELD.equals(c.FIELD) ) //whatever here
return true;
}
return false;
}
Take a look at Regarding Object Comparison.
Be aware that if you override equals()
you must also override hashCode()
. The equals/hashCode contract is that if two objects are equal they must have the same hash code.
If you plan to create subclasses of Person, use something like
if(obj!=null && obj.getClass() == Person.class)
rather than instanceof
The only reason to use getClass() rather than instanceof is if one wanted to assert that both references being compared point to objects of the exact same class rather than objects implementing the same base class. Say we have an Employee e and a Manager m (extends Employee). m instanceof Employee would yield true, m.getClass() == Employee.class would return false. In some cases the latter might be preferred, but rarely in case of comparison of instances in equals() or hashCode() methods.
One more point may be good to know that after you override equals() method (and also hashcode()) method you can to compare two objects of same class like follows:
Person p1 = new Person(); Person p2 = new Person();
....
if ( p1.equals( p2 ) )
{ // --- Two Persons are equal, w.r.t the fields you specified in equals method ---
}