我正在测试Strings,我提出了以下代码:
public static void main(String[] args){
StringBuilder sb1 = new StringBuilder("Cuba");
String str1 = sb1.toString();
// n1
System.out.println(str1 == str2);
}
在n1,如果我放置:
String str2 = sb1.toString();
我弄错了.但是,如果我放置:
String str2 = str1;
我明白了.
我不确定为什么会发生这种情况:两个代码都指的是同一个实例,因此两个输出都必须为true.
知道为什么两个输出都不同吗?我知道如何比较字符串,我只是对结果不同的原因感到好奇.
解决方法:
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
所以每次调用它时都会返回一个新的String.
当你设置str2 = str1时,它们是同一个实例,所以==返回true.但是,当你设置str2 = sb1.toString()时,它会被设置为一个新的String(具有相同的内容),所以==返回false.
这实际上是在toString() Javadoc(强调我的)中指定的:
Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.
请注意,您不应该使用==来比较字符串开头(参见this question).
标签:java,stringbuilder,string
来源: https://codeday.me/bug/20190528/1168347.html