代码如下
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的地址不是一个??

解决方案 »

  1.   

    试试看:public   class   Test   extends   TestCase   { 
    public   void   test1()   { 
    String   a   =   new   String("a").intern(); 
    String   b   =   new   String("a").intern(); 
    super.assertEquals(true,   a==b); 

      

  2.   

    我知道加了intern()后会相等, 但是就是想不通为什么第一种情况不行。在声明变量a的时候因该就已经在字符串池里面有了"a"了啊,第二次声明b怎么就不会用同样的字符串??
      

  3.   

        /**
         * 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()&nbsp;==&nbsp;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 &sect;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里面——个人是这么认为的
      

  4.   

    new 出来的不是在pool里面的哦!!
      public static void main(String[] args) {
        String   a   =   "a"; 
        String   b   =   new   String("a").intern(); 
        System.out.println(a==b);
      }
      

  5.   

    我认为应该是new String("a") 和 "a"的区别
    第二个指向的是"a"(应该是所谓存在于字符串池中的String)
    而第一个是new String("a") (此处为一个引用对象,而不是基础类型)
    所以不等
      

  6.   

    API里是这样描述的:
    当调用 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"的引用并返回 所以就会相等