共同学习Java源码--常用数据类型--String(四)

来源:互联网 发布:数据挖掘十大算法答案 编辑:程序博客网 时间:2024/05/17 22:29
    void getChars(char dst[], int dstBegin) {
        System.arraycopy(value, 0, dst, dstBegin, value.length);

    }

这个方法是将String对象的char数组value从下标为0的索引开始复制到char数组dst中,dst从dstBegin下标开始填充,复制的元素个数为value的长度。

    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

这个方法和上面的类似,只是让用户自行输入value从哪个下标开始复制,到哪个下标结束复制。

    public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }

    public byte[] getBytes(Charset charset) {
        if (charset == null) throw new NullPointerException();
        return StringCoding.encode(charset, value, 0, value.length);
    }

这两个方法都是将String对象以指定编码打散成byte数组并且是从char数组value的0开始,到数组结尾。只是两个方法接收的参数不一致,但原理大致相同。

    public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }

这个方法则是以默认编码将String对象打散成byte数组。



0 0