JDK1.7 String类中构造方法String(char value[], int offset, int count)源代码分析

 String类中部分成员变量定义如下:

/** The value is used for character storage.这个值用于字符存储 */
    private final char value[];

 String类中构造方法String(char value[], int offset, int count)源代码如下:

    /**
     * Allocates(分配) a new {@code String} that contains(包含) characters from a subarray
     * of the character array argument. The {@code offset} argument is the
     * index of the first character of the subarray and the {@code count}
     * argument specifies the length of the subarray. The contents of the
     * subarray are copied; subsequent modification of the character array does
     * not affect the newly created string.
     *
     * @param(参数)  value
     *         Array that is the source(来源) of characters
     *
     * @param  offset
     *         The initial(最初的) offset
     *
     * @param  count
     *         The length
     *
     * @throws  IndexOutOfBoundsException
     *          If the {@code offset} and {@code count} arguments index
     *          characters outside the bounds of the {@code value} array
     */
	 //offset表示第一个被截取的字符在数组value[]中的下标,count表示从此字符开始向后截取的字符的数量
	 //将value[]数组按照传入的下标和指定的截取数组数据的数量进行截取,并且创建一个内容为此的string对象
    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.
	//可以举具体例子进行理解offset不能大于value.length - count
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
	//copyOfRange( , , )将指定数组的指定范围复制到一个新数组
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

猜你喜欢

转载自blog.csdn.net/My_name_is_ZwZ/article/details/81836696
int