天天看點

java裡equal與equals_Java中關于==與equal和equals的差別

例子i:

string1="aaa";

string2="aaa";

String string3=new String("aaa");

String string4=new String("aaa");

string1==string2 // true; .

string1.equals(string2);//true;

string3==string4;//false 因為用new建立了2個對象,是以是兩個不同的記憶體位址

string3.equals(string4);//true 而String類的是不可改變的,是以會指向同一個記憶體位址,是以傳回為true

equals()是object的方法,是以隻是适合對象,不适合于基本類型,equals()預設是用"=="比較兩個對象的記憶體位址,如果想要比較兩個對象的内容,要重寫equals()方法才可...而==可以比較兩個基本類型,也可以是對象...

String的equals()方法重寫:

public boolean equals(Object object){

if( this==anObject)

{return true;}

if(anObject instancdOf String)

{String anotherString =(String)anObject;

int n= count;

if(n==anotherString.count)

{ char V1[]=value;

char V2[]=anotherString.value;

int i=offset;

int j=anotherString.offset;

while(n--!=0)

{ if (v1[i++]!=V2[j++]

return false;}

return true;}

}

return false;

}

總而言之:在類對象中 equals()方法比較的是對象的值,==比較的是對象.即為對象的引用(即為記憶體位址)一些特殊情況下equals()是重寫了方法咯..

equal:是用來比較兩個對象内部的内容是否相等的,由于所有的類都是繼承

自java.lang.Object類的,是以如果沒有對該方法進行覆寫的話,調用

的仍然是Object類中的方法,而Object中的equal方法傳回的卻是==

的判斷,是以,如果在沒有進行該方法的覆寫後,調用該方法是沒有

任何意義的。

==:是用來判斷兩個對象的位址是否相同,即是否是指相同一個對象。比較的

是真正意義上的指針操作。

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