Java重写Object equals()方法 [英] Java override Object equals() method

查看:155
本文介绍了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
}

这篇关于Java重写Object equals()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆