Java中的Clone() [英] Clone() in java
本文介绍了Java中的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?
推荐答案
clone
是Object类的一种方法.为了使一个类可克隆",它应该实现标记 Cloneable
接口. String
类无法实现此接口,并且不会覆盖clone方法,因此会导致错误.
clone
is a method of the Object class. 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.
我希望上面的代码段是出于教育目的,因为鉴于以下情况,您永远不会觉得需要在Java字符串中调用 clone
:
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:
- Java中的字符串是不可变的.随时在方法/类之间共享它们
- 已经存在一个构造函数
new String(String)
,其作用类似于复制构造函数,几乎等效于您的clone()
调用.
- 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 yourclone()
call.
这篇关于Java中的Clone()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文