1、判斷地址是否相等 用:==
Object類作為所有類的超類,而Object類的equals方法是直接比較地址的,源碼如下:
public boolean equals(Object obj) { return this == obj; }
2、判斷值是否相等 用:equals方法
equals() 方法用于將字符串與指定的對(duì)象比較。
語法
public boolean equals(Object anObject)
參數(shù)
anObject — 與字符串進(jìn)行比較的對(duì)象。
返回值
如果給定對(duì)象與字符串相等,則返回 true;否則返回 false。
public class Test { public static void main(String args[]) { String Str1 = new String("runoob"); String Str2 = Str1; String Str3 = new String("runoob"); boolean retVal; retVal = Str1.equals( Str2 ); System.out.println("返回值 = " + retVal ); retVal = Str1.equals( Str3 ); System.out.println("返回值 = " + retVal ); } }
以上程序執(zhí)行結(jié)果為:
返回值 = true
返回值 = true