java的字符串复制,我应该如何在Java中复制字符串?

String s = "hello";

String backup_of_s = s;

s = "bye";

At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).

But is it really safe to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :

String s = "hello";

String backup_of_s = new String(s);

s = "bye";

In other words, what's the difference (if any) between these two snippets?

EDIT - the reason why the first snippet is safe:

Let me just explain things with a little more detail, based on the good answers already provided (which were essentially focused on the question of difference of performance between the 2 snippets):

Strings are immutable in Java, which means that a String object cannot be modified after its construction.

Hence,

String s = "hello"; creates a new String instance and assigns its address to s (s being a reference to the instance/object)

String backup_of_s = s; creates a new variable backup_of_s and initializes it so that it references the object currently referenced by s.

Note: String immutability guarantees that this object will not be modified: our backup is safe

Note 2: Java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable (backup_of_s in this case)

Finally, s = "bye"; creates another String instance (because of immutability, it's the only way), and modifies the s variable so that it now references the new object.

解决方案

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值