Java重写Object equals()方法
问题描述:
如何覆盖对象类中的equals方法?
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){
}
我想将参数obj转换为Person类型,但是如果我这样做(Person)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
}