首先感谢进来看的朋友!谢谢你们抽出时间来看我的问题!
   String str1 = "hello";
   String str2 = new String("hello");
   print(str1 == str2)//返回false 
   上面这个返回false很必然,因为一个指向常量池 一个指向堆中的对象。但我的问题来了:
   我想弄明白new出来的String是怎么找到自己的"hello"的,是在堆中有一份拷贝?还是说,自己的对象里有一个引用指向常量池中的"hello"?那么这个"hello"会不会重新建一个空间存放呢?还是说和str1指的是同一个?看个例子:
   String str1 = "hello";
   String str2 = "hello";
   String str3 = new String("hello");
   String str4 = new String("hello");
   到这里 内存中是不是这样:
   常量池中只有一个"hello"
   栈中有4个引用 分别是str1  str2  str3  str4
   堆中有两个String类的对象  str3和str4分别指向
  
   还是那个问题 str3和str4中的数据 是在哪?指向常量池?还是自己的对象中有拷贝?

解决方案 »

  1.   

    去看String类的构造方法
    pubilc String(String orig)
    的代码就明白了
      

  2.   

    我觉得应该是  str1和str都是指向常量,所以这两个引用是相等的,而str3和str4是对前面那个常量的两份拷贝。所以我觉得hello这个字符串应该存了有三份。
      

  3.   


    /*
     * @(#)String.java 1.204 06/06/09
     *
     * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
     * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     */
    public String(String original) {
    int size = original.count;
    char[] originalValue = original.value;
    char[] v;
       if (originalValue.length > size) {
          // The array representing the String is bigger than the new
          // String itself.  Perhaps this constructor is being called
          // in order to trim the baggage, so make a copy of the array.
                int off = original.offset;
                v = Arrays.copyOfRange(originalValue, off, off+size);
      } else {
          // The array representing the String is the same
          // size as the String, so no point in making a copy.
        v = originalValue;
      }
    this.offset = 0;
    this.count = size;
    this.value = v;
        }
    这是Java的public String(String original)构造方法的源代码
    对象的value定义是:private final char value[];
    这么看来应该是在堆中的..那么string这个对象还有个引用指向这个char数组么?
      

  4.   

    明白了...string对象中的char  value[]本身就是个成员了。。就是这个它指向了堆中的字符串..
      

  5.   

    说的有点道理
    不过通过看string类构造方法的源代码我想现在应该是这样了.
    既然常量池中已经有一个"hello"了,那么就是这么一个.
    str1 和 str2都指向它
    对于str3 和 str4都是用构造方法来构造的,传进的参数是"hello"
    那么这个时候就会有个指向数据区中"hello"的引用,也就是形参original
    构造函数完成后,string对象中的value这个成员会指向在堆中新分配的一片空间,这个空间实际就是 数据区中"hello"的拷贝。小弟是这么认为的,请各位大哥看看对不对!在此先谢谢各位了!
      

  6.   

    只要new了  数据就存在堆里  常量 变量 方法 都存在栈里
      

  7.   

    “对象的value定义是:private final char value[]; 
    这么看来应该是在堆中的”为什么?
      

  8.   

    “对象的value定义是:private final char value[]; 
    这么看来应该是在堆中的”为什么?
      

  9.   

    Java中除了那 4类8种基本类型  其他都是引用类型
    这个char value[]也是引用类型,实际上是在堆中分配空间的。value只是在栈上的一个引用
      

  10.   

    string 对象的理解进行时,你看看,对你会有帮助。
      

  11.   

    http://www.blogjava.net/cheneyfree/archive/2008/05/12/200088.html