java输入stringbuild_java – 在同一个StringBuilder实例上调用toString时的不同输出

我正在测试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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值