【发布时间】:2021-08-04 03:31:22
【问题描述】:
我正在阅读OpenJDK中String.java的源码jdk16u。
它的一个构造函数如下所示:
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.value = "".value;
this.coder = "".coder;
}
显然.value 指的是这个私有的byte 数组:
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
这意味着当我们使用 String() 作为构造函数时,this.value 引用了"".value. 但是,我找不到"".value 的确切定义。在我看来,这像是一个循环定义。
编辑:这不是循环定义。我的意思是Java怎么知道“”表示空字符串。
【问题讨论】:
-
使用
"".value只会导致字符串为空字符序列,而不是可能导致各种问题的未定义值。 -
"".value的定义是“空字符串的value字段”。这个循环怎么样?请注意,this与""不是同一个对象。 -
@sorfiend 到底在想什么问题?因为我觉得这个构造函数真的很蠢
-
唯一的用例是当你想定义一个新的空字符串,而不是一个文字。当正是我无法理解时
-
@sorfiend 你的意思是说当计算机编译代码“”.value的时候,它会检测到“”是一个空字符串,所以它会创建一个空字符串对象,并将它的值初始化为一个char[ 0](新字符[]{})