String类中一个特殊的构造函数String(char[] value, boolean share)

在java的String类中,有这么一个特殊的构造函数:

/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*/
String(char[] value, boolean share) {
    // assert share : "unshared not supported";
    this.value = value;
}

它有一个额外的share参数,但是却没有使用到这个参数,这是为什么呢?带着疑问阅读了注释,原因如下:

在String类中,已经有一个入参为char数组的构造函数:

/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* @param  value
*         The initial value of the string
*/
public String(char value[]) {
    this.value = Arrays.copyOf(value, value.length);
}

正常的构造函数操作是,将入参的char数组拷贝一份到String类中自己的value数组。

String(char[] value, boolean share)这个构造函数的操作为了速度及内存上的考虑,不进行数组的拷贝,而是直接将入参的数组指针直接赋值给String类中的value,减少了数组拷贝带来的时间和内存上的消耗。但是因为入参完全一样,构造函数无法重载,所以为了区分增加了一个没有使用的参数。

虽然String(char[] value, boolean share)这个构造函数带来了速度和内存上的优化,但是却存在问题,一旦传入的char数组在外部被修改了,这个字符串对象的值也就被修改了。所以这个构造函数的访问修饰符被定为默认(即不写),而String类又是final类,所以这个方法只能被java内部的同一个包下的类使用。目前知道的使用位置为:StringBuffer类中的toString方法。

参考资料:https://www.cnblogs.com/yy1024/p/5594097.html


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍