日期:2014-05-20  浏览次数:20587 次

String 的构造方法String(String original)
看String的构造方法
Java code

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;
    }


看文档和其他书一般是不建议我们使用这个构造方法的,因为没有必要.
代码里我不明白的是if (originalValue.length > size)这个分支,会有这种情况出现吗?count和字符数组的长度不总是相等的吗?
为什么要这么设计呢?
谢谢回答.

------解决方案--------------------
帮顶一下~我是一只小菜鸟~飞啊飞~
------解决方案--------------------
个人感觉可能只是为了保险所以才那么写的吧 就好像有时候我们写程序的时候也会这样 凭判断和推算都感觉不会有这种情况 但是又不敢完全确定(比如说哥德巴赫猜想 随便想个数代入都可以成立 但是目前也只证明到“1+2” 因为不能完全证明“1+1”所以还不能说哥德巴赫猜想就是对的) 所以为了保险就貌似“画蛇添足”般的把判断条件写上 个人意见 我是一只小菜鸟~继续飞~
------解决方案--------------------
这个与其中的 offset 有关,你找一下,应该可以找到这个构造:

Java code
String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
}

------解决方案--------------------
嗯 估计是大企鹅把count和value弄混了...很少看见大企鹅提问啊...
------解决方案--------------------
正在努力学习中。。。
帮顶了。。。