对于String s = "abc";这个java语句,s指向常量池中的"abc"。但是在public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    private final char value[];
...
中,用char数组存放真正的字符串。我的问题是java究竟在何时以怎样的方式实现字符常量向字符数组的转换的?

解决方案 »

  1.   

    "abc" 就是一个共享的 String 对象,s 只需要指向它就行了。当发现需要 "abc" 时,这个对象就自动构造了,如果 String 的内部表示是字节数组的话,那这个数组这时候已经自动生成了。这里要注意 "abc" 只是我们源文件里的写法,编译器读了这个源文件之后就会了解我们的意思,然后将这个字符串对象的生成代码编译进 .class 文件中去。也就是说,这个对象是在编译器的领导下,由 Java 运行时生成的。
      

  2.   

    会不会跟这段有关系呢?/*
     * @(#)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;
        }