为什么String类不可克隆? [英] Why String class is not Cloneable?
本文介绍了为什么String类不可克隆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 String
类未实现 Cloneable
接口?
例如:(有时我们会编写这种类型的代码。)
For example: (We write this type of code sometimes.)
String s1 = new String("Hello");
String s2 = new String("Hello");
这里s1!= s2;
Here s1!=s2;
因此,如果可以的话,不要这样做:
So instead of doing this , if we could have done:
String s1 = new String("Hello");
String s2 = s1.clone();
这可能很容易。
推荐答案
String
类表示一个不变的字符串。克隆 String
是没有目的的。如果您认为需要克隆它,则可以重复使用相同的引用并获得相同的效果。
The String
class represents an immutable string. There would be no purpose to cloning a String
. If you feel that you need to clone it, then you can just reuse the same reference and achieve the same effect.
即使您可以克隆
s1
作为 s2
,然后 s1!= s2
仍为 true
。它们仍然是对不同对象的引用。
Even if you could clone
s1
as s2
, then s1 != s2
would still be true
. They'd still be references to distinct objects.
这篇关于为什么String类不可克隆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文