String构造器中 originalValue.length > size 发生的情况

  String构造器中有一段代码如下:

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

其中  originalValue.length > size 这段代码让人有点难以理解,什么情况下会发生呢?

String内部有三个属性

 /** The value is used for character storage. */
    private final char value[];

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;

subString 方法

 public String substring(int beginIndex) {
	return substring(beginIndex, count);
    }
    
 public String substring(int beginIndex, int endIndex) {
	if (beginIndex < 0) {
	    throw new StringIndexOutOfBoundsException(beginIndex);
	}
	if (endIndex > count) {
	    throw new StringIndexOutOfBoundsException(endIndex);
	}
	if (beginIndex > endIndex) {
	    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
	}
	return ((beginIndex == 0) && (endIndex == count)) ? this :
	    new String(offset + beginIndex, endIndex - beginIndex, value);
    }

其中value为存放字符的char数组,offset为偏移量,count为长度,当调用subString 方法时会返回一个偏移量为offset + beginIndex,长度为endIndex - beginIndex,value不变(即char数组不变)的String

举个例子:

        String a = "012345";
        String b = a.substring(2);
        String c = new String(b);

其中 a的value为012345的数组,offset为0,coun为6

       b的value为012345的数组,offset为2,count为4

当实例化c时就发生了originalValue.length > size即b.value.length>b.count的情况.


参考资料:http://stackoverflow.com/questions/12907986/how-could-originalvalue-length-size-happen-in-the-string-constructor

转载于:https://my.oschina.net/wancaibida/blog/191154

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值