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

其中String类中定义部分成员变量的源代码:

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

构造方法String(int[] codePoints,int offset,int count)的源代码以及方法前的注释如下:

 /**
     * Allocates a new {@code String} that contains characters from a subarray
     * of the <a href="Character.html#unicode">Unicode code point</a> array
     * argument.  The {@code offset} argument is the index of the first code
     * point of the subarray and the {@code count} argument specifies the
     * length of the subarray.  The contents of the subarray are converted to
     * {@code char}s; subsequent modification of the {@code int} array does not
     * affect the newly created string.
     *
     * @param  codePoints
     *         Array that is the source of Unicode code points
	 *         数组,它是Unicode代码点的来源
     *
     * @param  offset
     *         The initial offset  初始偏移量
     *
     * @param  count
     *         The length
     *
     * @throws  IllegalArgumentException
     *          If any invalid Unicode code point is found in {@code
     *          codePoints}
     *
     * @throws  IndexOutOfBoundsException
     *          If the {@code offset} and {@code count} arguments index
     *          characters outside the bounds of the {@code codePoints} array
     *
     * @since  1.5
     */
	 //从数组下标为offset开始顺序取出数组codePoints[]中count个整数,并根据此uncode代码点所对应的字符创建一个string对象
    public String(int[] codePoints, 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.
        if (offset > codePoints.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }

        final int end = offset + count;

        // Pass 1: Compute(计算) precise(精确的) size of char[] 用于下面创建v数组时的数组长度的确定
        int n = count;
        for (int i = offset; i < end; i++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))//判断代码点是不是BMP(此方法在1.6之前没有)
                continue;
            else if (Character.isValidCodePoint(c))//确定指定的代码点是否是一个有效的Unicode代码点值
                n++;
            else throw new IllegalArgumentException(Integer.toString(c));
        }

        // Pass 2: Allocate(分配) and fill in(填充) char[]
        final char[] v = new char[n];//用于存储要转成string对象中字符的字符

        for (int i = offset, j = 0; i < end; i++, j++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))
                v[j] = (char)c;
            else
                Character.toSurrogates(c, v, j++);
        }

        this.value = v;
    }

猜你喜欢

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