今天寫點簡單點的吧,equals和==的作用都是作比較,但==是條件運算符,而equals是一個繼承了object類的方法,也就是說所有類都有一個equals方法,我們先來看一下equals方法在object類中的定義吧。
[java] view plain copypublic boolean equals(Object obj) { return (this == obj); } 顯然,equals比較的是兩個對象的地址,而我們通常需要比較的是兩個對象的內(nèi)容(例如Student類的姓名或者學(xué)號),因此我們一般會重寫該類的equals方法,像我們經(jīng)常使用的String類早已重寫了equals方法。以下是Student類的equals方法重寫:
[java] view plain copypublic boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }只有當(dāng)兩個對象的學(xué)號(id)相等時才能返回true,否則返回false。
總結(jié):==不能用于兩個對象(基本數(shù)據(jù)類型除外)內(nèi)容的比較,需要使用重寫后的equals方法!!
新聞熱點
疑難解答