java 中的克隆()
import java.util.*;
import java.lang.*;
public class Test{
public static void main(String[] argv){
String s1="abc";
String s2=(String) s1.clone();
}
}
为什么这个简单的测试程序不起作用?
import java.util.*;
import java.lang.*;
public class Test{
public static void main(String[] argv){
String s1="abc";
String s2=(String) s1.clone();
}
}
Why this simple test program doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
clone
是Object类的一个方法。对于“可克隆”的类,它应该实现标记Cloneable
接口。String
类没有实现此接口,也没有重写克隆方法,因此会出现错误。我希望上面的代码片段用于教育目的,因为您永远不会觉得需要对 Java 中的字符串调用
clone
,因为:new String(String)
,它的作用类似于复制构造函数,几乎相当于您的clone()
调用。clone
is a method of the Object class. For a class to be "cloneable" it should implement the markerCloneable
interface.String
class doesn't implement this interface and doesn't override the clone method hence the error.I hope the above snippet is for educational purposes because you should never feel a need to call
clone
on strings in Java given that:new String(String)
which acts like a copy constructor and is pretty much equivalent to yourclone()
call.Object.clone()
受到保护。这是一个使用起来很棘手的 API。通常,当通过扩大方法的可见性来扩展 Object 时,就会公开
clone()
。任何字符串上的克隆都没有什么意义,因为它既是最终的又是不可变的。
复制字符串是有原因的;可以通过以下方式完成:
Object.clone()
is protected. It is a tricky API to use.Usually one exposes
clone()
when one extends Object by broadening the method's visibility.Clone on any string has little meaning, since it is both
final
and immutable.There is a reason to copy a string; that can be done with:
克隆() 是 Object 类的受保护方法。如果您希望类可克隆,一般模式是实现 可克隆 并将该方法公开。
clone() is a protected method on the Object class. If you want a class to be cloneable the general pattern is to implement Cloneable and make that method public.
显然无法编译。
Object.clone
具有受保护的访问权限。It obviously couldn't be compiled.
Object.clone
has protected access.对于“可克隆”的类,它应该实现标记 Cloneable 接口。 String 类没有实现此接口,也没有重写克隆方法,因此会出现错误。
protected Object clone() 抛出CloneNotSupportedException 创建并返回该对象的精确副本(克隆)。
Java 中的字符串是不可变的。请随意在方法/类之间共享它们
已经存在一个构造函数 new String(String) ,它的作用类似于复制构造函数,几乎等同于您的 clone() 调用。
通常,当通过扩大方法的可见性来扩展 Object 时,就会公开 clone() 。
任何字符串上的克隆都没有什么意义,因为它既是最终的又是不可变的。
For a class to be "cloneable" it should implement the marker Cloneable interface. String class doesn't implement this interface and doesn't override the clone method hence the error.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
Strings in Java are immutable. Feel free to share them across methods/classes
There already exists a constructor new String(String) which acts like a copy constructor and is pretty much equivalent to your clone() call.
Usually one exposes clone() when one extends Object by broadening the method's visibility.
Clone on any string has little meaning, since it is both final and immutable.