我应该如何在Java中复制字符串? [英] How should I copy Strings in Java?

查看:202
本文介绍了我应该如何在Java中复制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    String s = "hello";
    String backup_of_s = s;
    s = "bye";

此时,备份变量仍然包含原始值hello(这是因为String的不变的权利?)。

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?

编辑 - 第一个片段安全的原因:

让我根据已经提供的好答案(主要关注2个片段之间的性能差异问题),更详细地解释一些事情:

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):

字符串在Java中是不可变的,这意味着String对象在构造后不能被修改。
因此,

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

String s =hello; 创建一个新的String实例并分配其地址到 s s 是对实例/对象的引用)

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

字符串backup_of_s = s; 创建一个新变量 backup_of_s 并初始化它以便它当前引用该对象由 s 引用。

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

注2:Java垃圾收集机制保证只要该对象被至少一个变量引用( backup_of_s 在这种情况下)

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)

最后, s =bye; 创建另一个String实例(因为不变性,这是唯一的方法),并修改 s 变量,以便它现在引用新对象。

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.

推荐答案

由于字符串是不可变的,b其他版本是安全的。然而,后者效率较低(它创建了一个额外的对象,在某些情况下复制了字符数据)。

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.

这篇关于我应该如何在Java中复制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆