Stringと定数プールの問題について

7182 ワード

面接は必須でしょうが、もう一つ漏れやすいところがあるようです.
全体的なプロセスは、このコードを実行した後、彼らの結果が何なのか、なぜ理解できないのかを明らかにします.
String a1 = new String("ab");
System.out.println(a1 == a1.intern());//false

String a2 = "ab";
System.out.println(a2 == a2.intern());// true
System.out.println(a2 == a1); // false
System.out.println(a2 == a1.intern()); // true

String a3 = "cd";
System.out.println(a3 == a3.intern());// true

String a4 = new StringBuilder().append("ef").append("gh").toString();
String a5 = a4.intern();
System.out.println(a4 == a5); // true

String a6 = new String("ij") + new String("k");
String a7 = a6.intern();
System.out.println(a6 == a7); // true

String a8 = "l" + "mn";
String a9 = a8.intern();
System.out.println(a9 == a8); // true
intern()メソッドについて:
Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.