代码如下
public class Test extends TestCase {
public void test1() {
String a = new String("a");
String b = new String("a").intern();
super.assertEquals(true, a==b);
}
}
既然intern是根据字符串池来判断,如果有相同的字符串则返回现成的,那么为什么a的地址和b的地址不是一个??
public class Test extends TestCase {
public void test1() {
String a = new String("a");
String b = new String("a").intern();
super.assertEquals(true, a==b);
}
}
既然intern是根据字符串池来判断,如果有相同的字符串则返回现成的,那么为什么a的地址和b的地址不是一个??
public void test1() {
String a = new String("a").intern();
String b = new String("a").intern();
super.assertEquals(true, a==b);
}
}
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class <code>String</code>.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this <code>String</code> object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this <code>String</code> object is added to the
* pool and a reference to this <code>String</code> object is returned.
* <p>
* It follows that for any two strings <code>s</code> and <code>t</code>,
* <code>s.intern() == t.intern()</code> is <code>true</code>
* if and only if <code>s.equals(t)</code> is <code>true</code>.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in §3.10.5 of the
* <a href="http://java.sun.com/docs/books/jls/html/">Java Language
* Specification</a>
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
是一个pool实现的,只有使用了intern()方法之后,才加到pool里面——个人是这么认为的
public static void main(String[] args) {
String a = "a";
String b = new String("a").intern();
System.out.println(a==b);
}
第二个指向的是"a"(应该是所谓存在于字符串池中的String)
而第一个是new String("a") (此处为一个引用对象,而不是基础类型)
所以不等
当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并返回此 String 对象的引用。很明显 当你String a = new String("a");时 池中并没有"a" 因此当执行String b = new String("a").intern();时并不会把"a"的引用给b 所以不会相等 但如2楼所写 String a = new String("a").intern(); 因为调用了intern()所以在没查到"a"的情况下会将"a"加入到池里 那接下来String b = new String("a").intern();就会找到"a"的引用并返回 所以就会相等