"aaaa".length();
谁能帮我分析下这个是怎么实现的,具体到api里面。

解决方案 »

  1.   

    String内部维护的是一个数组如下:
    private final char value[];
    其length()方法返回的private final int count;这个东西。
    每当生成一个String的时候这两个参数都是一定的。String a = "a";
    a = a + "a";
    其实大家都知道是新产生了一个String,而a的引用指向这个String而已。
    所以a可以获取他的count为1,而"a"的count也为1,产生的char value[] = {'a','a'}; count=2;
    所以length就为2了
      

  2.   

    "aaaa".length();你知道C++的指针吧 *p把*p指向这个字符串的首地址,然后移动指针 p++当指针为NULL,就不能移动了。这是长度也就出来了。
      

  3.   

    我只知道String是用char[]实现的。。
      

  4.   

    public int length() {
            return count;
        }
      

  5.   

    就是count前面是怎么赋值进去的?
      

  6.   

    String 是final 的, 其实就是char 的数据。 数组的长度是固定的。。固定 定 。。的
      

  7.   

    自己要具体到源码,而JAVA都是开源的为什么不自己去看源码呢????
      

  8.   

      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.
        v = new char[size];
          System.arraycopy(originalValue, original.offset, v, 0, 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;
        }