Java源码阅读计划(1) String<II>

自作多情 提交于 2019-12-03 11:59:15

String的构造函数

String有很多构造函数,不同种类的有不同的作用,接下来我们一个个看下去

  • 1
public String() {
        this.value = "".value;
}

初始化一个String对象,使其表示一个空字符串序列,由于字符串的不可变性,这个方法其实是不必要的。

  • 2
    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

简单易懂,除非需要显式复制,否则这个方法也是不必要,因为字符串的不可变性。

  • 3
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

依然很简单,不过要注意字符数组的后续修改不会影响新创建的字符串。

  • 4
    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

这个方法是从字符数组中截取一段作为value的值,这里面做了一些关于长度与角标的判断,另外,同样的,这里形参char[]的改变与其之前所创建的String对象已经没有关系了

  • 5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!