<small>
public class Object
類 Object 是類層次結(jié)構(gòu)的根類。每個(gè)類都使用 Object 作為超類。所有對(duì)象(包括數(shù)組)都實(shí)現(xiàn)這個(gè)類的方法。
1、equals()
相等于==
Object 類的 equals 方法實(shí)現(xiàn)對(duì)象上差別可能性最大的相等關(guān)系;即,對(duì)于任何非空引用值 x 和 y,當(dāng)且僅當(dāng) x 和 y 引用同一個(gè)對(duì)象時(shí),此方法才返回 true(x == y 具有值 true)。
注意:當(dāng)此方法被重寫時(shí),通常有必要重寫 hashCode 方法,以維護(hù) hashCode 方法的常規(guī)協(xié)定,該協(xié)定聲明相等對(duì)象必須具有相等的哈希碼。
2、toString()
返回該對(duì)象的字符串表示
Object 類中的 toString 是類名@16進(jìn)制的 哈希值
//如何直觀的看到該對(duì)象的屬性?重寫方法
public String toString(){
//標(biāo)準(zhǔn)型
return this.getClass().getName()+
//簡(jiǎn)單型
"@["name=this.name"+age=this.age]
}
String str="123456";
System.out.println(str.toString);//123456
pe0.toString;//類名@哈希值
注意:Object中的 euqals 和 toString 與 String 中的euqals 和 toString 是不同的,String 類已經(jīng)將這兩個(gè)方法進(jìn)行了重寫
toString 和 equals 方法的重寫可以參照如下:
/*
* 為了能夠更加直觀的打印出對(duì)象的內(nèi)容。
* 則必須重寫Object中的toString方法
*/
@Override
public String toString(){
//標(biāo)準(zhǔn)型
return //this.getClass().getName()+
//"@" +
//簡(jiǎn)易型
"[" +
"name="+this.name+"," +
"age="+this.age+
"]";
}
/**
* 從值面量上,可以看出,peo于peo1是相等的。
但是Object的equals方法滿足不了,所以我們需要重寫。
equals方法判斷的是兩個(gè)對(duì)象內(nèi)容。
* @return
*/
@Override
public boolean equals(Object other){
if(other == null){//判空
return false;
}
if(other == this){//同一個(gè)對(duì)象
return true;
}
if(other instanceof People){//類型匹配
//同類型對(duì)象才可比。
People otherPeo = (People)other;
//如果名字相同、年齡相同,才說(shuō)明兩個(gè)對(duì)象值相同
return this.name.equals(otherPeo.name)
&&
this.age == otherPeo.age;
}
return false;
}