JDK之String源码解读(一)

版权声明:本文为博主原创文章,欢迎转载,转载请标明出处。 https://blog.csdn.net/qq_32523587/article/details/86550783

目录

类的属性

String()

String(String original)

String(char value[])

String(char value[], int offset, int count)

String(int[] codePoints, int offset, int count)


String类表示字符串。所有Java程序中的字符串文字,如“ABC”,都是该类的实例。

String是常量;它们的值在被创建之后不能更改。StringBuffer支持可变字符串。因为字符串对象是不可变的,所以可以共享它们。例如:

String str = "abc";

等价于

char data[] = {'a', 'b', 'c'};
String str = new String(data); 

Java语言为String提供了特殊的支持。串联运算符+,用于转换其他对象到字符串。通过Stringbuilder(或Stringbuffer)实现了字符串连接类及其append方法。

类的属性

//内部是字符数组
private final char value[];

//String的hashCode,默认值是0
private int hash;

String()

作用:无参的构造函数。

String(String original)

作用:将String original赋值给当前String。

String(char value[])

作用:将字符数组赋值给当前String。

String(char value[], int offset, int count)

作用:将字符数组指定位置处的指定长度个字符赋值给当前String。

String(int[] codePoints, int offset, int count)

public String(int[] codePoints, int offset, int count) {
        //起始位置小于0,抛出异常
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }

        if (count <= 0) {
            if (count < 0) {
                //赋值的内容小于0,抛出异常
                throw new StringIndexOutOfBoundsException(count);
            }
            //赋值的内容长度等于0,将当前对象初始化成空字符串
            if (offset <= codePoints.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > codePoints.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }

        //int[] codePoints内要赋值的内容的结束位置
        final int end = offset + count;

        // Pass 1: Compute precise size of char[]
        int n = count;
        //遍历要插入的数组int[] codePoints
        for (int i = offset; i < end; i++) {
            int c = codePoints[i];
            //如果是BMP类型的代码点,则跳过本次循环。因为BMP类型的本身就只占用1个char
            if (Character.isBmpCodePoint(c)) 
                continue;
            //如果是valid的代码点,则会占用两个char的长度,因此总长度的+1
            else if (Character.isValidCodePoint(c))
                n++;
            else throw new IllegalArgumentException(Integer.toString(c));
        }

        // Pass 2: Allocate and fill in char[]
        //创建一个新的字符数组,长度是前面计算过的长度
        final char[] v = new char[n];

        //遍历要插入的数组int[] codePoints
        for (int i = offset, j = 0; i < end; i++, j++) {
            int c = codePoints[i];
            //如果是BMP类型的代码点,则直接赋值
            if (Character.isBmpCodePoint(c))
                v[j] = (char)c;
            //如果不是BMP类型的代码点,则需要占用2个char长度,调用Character.toSurrogates()来赋值
            else
                Character.toSurrogates(c, v, j++);
        }

        this.value = v;
    }

作用:将整型数组指定位置处的指定长度个字符赋值给当前String。

其中,toSurrogates(int codePoint, char[] dst, int index)会赋值两次,即赋值lowSurrogate和highSurrogate给字符数组。

猜你喜欢

转载自blog.csdn.net/qq_32523587/article/details/86550783