受到关于这个问题的评论的启发,我很确定Java String是在运行时而不是编译时间实现的 - 当然,事实上可以在不同的时间编译类,但在运行时仍然会指向相同的引用.
我似乎无法找到任何证据支持这一点.谁能证明这一点?
如果不可变类对象副本将等于原始副本那么为什么StringJava 中的类具有复制构造函数?这是一个错误还是这个实施背后的原因?在Java文档中,它被指定为:
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
public String(String original) {
....
....}
Run Code Online (Sandbox Code Playgroud) 请参阅以下代码.
String s = "Monday";
if(s.subString(0,3).equals("Mon"){}
String s2 = new String(s.subString(0,3));
String s3 = s.subString(0,3);
Run Code Online (Sandbox Code Playgroud)
我知道第2行仍将指向"星期一",并且有一个新的String对象,其偏移量和计数设置为0,3.
第4行将在字符串池中创建一个新的字符串"Mon"并指向它.
但不确定第5行是否会表现为第2行或第4行.
如果第2行或第4行我错了也请更正..