zoukankan      html  css  js  c++  java
  • String构造函数originalValue.length>size 它发生

    最近观看Jdk6于String源代码被发现String这种施工方法有。源内容如下面:

    public String(String original) {
    	int size = original.count;
    	char[] originalValue = original.value;
    	char[] v;
      	if (originalValue.length > size) {
                int off = original.offset;
                v = Arrays.copyOfRange(originalValue, off, off+size);
     	} else {
    	    v = originalValue;
     	}
    	this.offset = 0;
    	this.count = size;
    	this.value = v;
        }

    这时就对originalValue.length > size这个不解啊。故网上搜寻原因。

    发如今stackoverflow上有人提到这个问题。

    还有个国内的文章也说了这个问题。

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

    2  http://www.kankanews.com/ICkengine/archives/99041.shtml

    看了上面的两篇文章的说明。我彻底的明确了。

    原来是这样啊。来看看jdk6中String的subString方法。

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

    // Package private constructor which shares value array for speed.
        String(int offset, int count, char value[]) {
    	this.value = value;
    	this.offset = offset;
    	this.count = count;
        }

    看看上面的源代码。发现使用substring方法后新的String对象的字符数组还是原来对象的字符数组。

    这样就出现了originalValue.length > size这个问题。

      String s1="hello world";
      String s2=s1.substring(6);
      String s3=new String(s2);
            
    分析上面的代码 s2的属性char[] value任然是原来s1的属性char[] value={'h','e','l','l','o',' ','w','o','r','l','d'}。s2的属性offset为6,count为5.在new String(s2)时originalValue.length=11>count=5。

    故我们可知在这种情况下会出现本文讨论的问题。

     



    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    搜狗图片抓取,主要以图集类进行抓取
    使用mongo进行去重操作
    爬虫实战01_淘宝模拟登录
    Linux常用命令02(远程管理)
    Linux常用命令01(文件和目录)
    Linux终端命令格式
    常用Linux命令的基本使用
    闭包与私有变量
    三栏布局的几种方法
    redux和react-redux小记
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4851951.html
Copyright © 2011-2022 走看看