import java.util.*;
public class Main{
public static void main(String[] args)
{
person staff=new person("lol");
person man=new person("xxx");
System.out.println(man);//默认man.toString()
if(staff.equals(man))
{
System.out.println("yes");
}else{
System.out.println("no");
}
}
}
class person{
private String name;
public person(String name)
{
this.name=name;
}
public String getname()
{
return this.name;
}
public String toString()
{
return getClass()+" "+getname();
}
public int hashcode()
{
return Objects.hash(getname());
}
public boolean equals(Object otherobject)
{
if(this==otherobject) return true;
//若两者引用同一块数据区域,返回真
if(otherobject==null) return false;
//若两者都为空,则返回假
if(getClass()!=otherobject.getClass()) return false;
//也可以用instanceof方法
//若两者类名不相同,返回假
var other =(person)otherobject;//将otherobject强制类型转换,否则无法使用person类的数据和方法
return Objects.equals(this.name,other.name);
}
}
object类中equals和tostring重写,hash函数,getClass函数
最新推荐文章于 2024-06-15 18:04:35 发布