百度的面試官問html
String A="ABC";面試
String B=new String("ABC");post
這兩個值,A,B 是否相等,若是都往HashSet裏面放,能放下嗎?this
答:(a)A==B 的判斷爲false;url
(b)A.equals(B)爲true ;由於值相等,因此都往HashSet裏面放不下,只能放一個 spa
String A = "ABC";內存會去查找永久代(常量池) ,若是沒有的話,在永久代中中開闢一起內存空間,把地址付給棧指針,若是已經有了"ABC"的內存,直接把地址賦給棧指針;指針
所以 code
String str1="aa";orm
Srting str2="aa";htm
String Str3="aa";
....
這樣下去,str1==Str2==str3;會一直相等下去,(a) ==的判斷, (b) equals()的判斷;都相等,由於他們的地址都相等,所以只在常量池中有一分內存空間,地址所有相同;
而String str = new String("a");是根據"a"這個String對象再次構造一個String對象;在堆中重新new一起內存,把指針賦給棧,
將新構造出來的String對象的引用賦給str。 所以 只要是new String(),則,棧中的地址都是指向最新的new出來的堆中的地址,
(a)「」==「」 是判斷地址的,固然不相同;
(b)至於equals,String類型重寫了 equals()方法,判斷值是否相等,明顯相等,所以 equals 是相等的;
這是String 重寫的equals:
* @see #compareTo(String) * @see #equalsIgnoreCase(String) */ public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String) anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
public class StringDemo2 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = "hello"; System.out.println(s1 == s2);// false System.out.println(s1.equals(s2));// true } } **運行結果:** > false > true
代碼詳解
public class StringDemo1 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1 == s2);// false System.out.println(s1.equals(s2));// true String s3 = new String("hello"); String s4 = "hello"; System.out.println(s3 == s4);// false System.out.println(s3.equals(s4));// true String s5 = "hello"; String s6 = "hello"; System.out.println(s5 == s6);// true System.out.println(s5.equals(s6));// true } }
s1~s6用equals()的比較不解釋,都是比較的值,均爲true。如下講解==
public class StringDemo4 { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; System.out.println(s3 == s1 + s2);// false System.out.println(s3.equals((s1 + s2)));// true System.out.println(s3 == "hello" + "world");//false System.out.println(s3.equals("hello" + "world"));// true } }
equals()比較方法不解釋,比較值,均相等,均爲true。