Java中的equals学习小结
?
? Java中的equals是十分重要的,和= =要區別開來,最近在看孫衛琴的JAVA面向對象編程一書,覺得對其闡述寫的不錯,所以現在小結其
主要內容,而且要將 = =和 equals列為重要的對比概念來學習
1、聲明格式
??? public? boolean equals(Object obj)
?? 其比較規則為:當參數obj引用的對象與當前對象為同一個對象時,就返回true,否則返回false.
比如以下兩個對象animal1和animal2,引用不同的對象,因此用==或equals()方法比較的結果為false;而animal1和animal3變量引用同一個DOg對象,因此用= =或者equals()方法比較的結果為true.
?? Animal? animal1=new Dog();
?? Animal? animal2=new? Cat();
?? Animal animal3=animal1;
則animal1==animal2?? (FALSE)
?? animal1.equals(animal2)? (false)
?? animal1==animal3?? (true)
?? animal1.equals(animal3)?? (true)
而JDK類中有一些類覆蓋了oject類的equals()方法,比較規則為:如果兩個對象的類型一致,并且內容一致,則返回true,這些類有:
java.io.file,java.util.Date,java.lang.string,包裝類(Integer,Double等)
比如
Integer? int1=new Integer(1);
Integer int2=new Integer(1);
String str1=new String("hello");
String str2=new String("hello");
int1==int2?? 輸出:false,因為不同對象
int1.equals(int2)?? 輸出:TRUE
str1==str2?? (false)
str1.equals(str2)?? (true)
? 當然,可以自定義覆蓋object類的equals()方法,重新定義比較規則。比如,下面Person類的equals()比較規則為:只要兩個對象都是Person類,并且他們的屬性name都相同,則比較結果為true,否則返回false
public class Person{
?? private String name;
?? public Person(String name)
? {
???? this.name=name;
?? }
public boolean equals(Object o)
{
? if (this==0) return true;
if (!o instanceof Person) return false;
final Person other=(Person)o;
if (this.name().equals(other.name()))
??? return true;
else
? return false;
}
}
注意,在重寫equals方法時,要注意滿足離散數學上的特性
1、自反性?? :對任意引用值X,x.equals(x)的返回值一定為true.
2??? 對稱性:?? 對于任何引用值x,y,當且僅當y.equals(x)返回值為true時,x.equals(y)的返回值一定為true;
3??? 傳遞性:如果x.equals(y)=true, y.equals(z)=true,則x.equals(z)=true
4?? 一致性:如果參與比較的對象沒任何改變,則對象比較的結果也不應該有任何改變
5?? 非空性:任何非空的引用值X,x.equals(null)的返回值一定為false
轉載于:https://www.cnblogs.com/OOAbooke/archive/2012/01/12/2321056.html
總結
以上是生活随笔為你收集整理的Java中的equals学习小结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF系列一
- 下一篇: 浅析堡垒机概念及工作原理(转)