與equals的區別

2021-09-25 17:01:05 字數 1777 閱讀 5280

簡單總結一下區別

//==

基本型別比較的是值

引用型別比較的是位址

//equals()

只對於引用型別而言,因為equals()是object 的方法,如果物件不對他進行重寫,則他們就直接繼承object的,比較的是物件的位址值,

如果對他進行重寫就按照他重寫的規則,例如string integer就重新定義了,它比較的是內容

檢視api文件可知string中重新定義了equals()語法

再舉乙個例子

package 面試寶典;

例3

答案是這樣的

為什麼

integer b =3,c=3;

system.out.println(bc);//是true;

而integer e=200,f=200;

system.out.println(ef);//會是false呢

這是是因為第乙個,==對於引用型別比較的是位址值,b.c都為棧區變數位址一致,所以返回true;

而 e,f 根據integer原始碼;

` public static integer valueof(int i)

`integer實際上先從integercache裡取資料,如果資料值不在integercache.low(-128)和integercache.high(127)範圍內,會new新的integer物件,所以值超過127的都建立新的物件例項,兩者物件值相等,但位址不一樣,「==」返回false,由於integer重寫的equals,實現值比對。所以"equals"返回true。同理string也一樣道理

private static class integercache  catch( numberformatexception nfe) 

}high = h;

cache = new integer[(high - low) + 1];

int j = low;

for(int k = 0; k < cache.length; k++)

cache[k] = new integer(j++);

// range [-128, 127] must be interned (jls7 5.1.7)

assert integercache.high >= 127;

}private integercache() {}

}

與equals的區別

注意 當比較兩個基本資料型別的變數是否相等時 基本資料型別包括 byte short int long float double 當它們的值相同時,則 結果就為true eg public class class6 1 public static void main string args stri...

與equals的區別

public class equaltest 執行結果為 t1 t2 false t1 t2 t3 true t3 t4 true i1.equals i2 false i3.equals i1 i2 true i3.equals i4 true st1 st2 false st1 st2 st3 ...

與 equals的區別

與equals都是比較兩個變數得到true或false。在進行比較時,先說說記憶體,記憶體分為堆和棧。基本資料型別中,是把值存在棧中,把值傳遞給變數,這種傳遞叫值傳遞。引用資料型別中,是在棧中存位址,堆中存的new的物件,給變數賦值傳遞時,傳的是位址,這種傳遞叫引用傳遞。基本資料型別 int a 1...