java在接口Cloneable中找不到符号clone()
我正在尝试克隆可克隆列表:
public static <T extends Cloneable> List<T> cloneList(List<T> list)
{
List<T> out = new ArrayList<T>();
for(int i=0;i<list.size();i++)
{
out.add((T)((T)list.get(i)).clone());
}
return out;
}
这会引发错误:
Helpers.java:40: error: cannot find symbol
out.add((T)((T)list.get(i)).clone());
^
symbol: method clone()
location: interface Cloneable
为什么,;clone()
接口的唯一方法是Cloneable
吗
# 1 楼答案
Cloneable
是一个marker接口,clone()方法在对象类中,因此您应该根据需要重写类中的clone()方法,并且您还必须实现Cloneable接口来告诉JVM对象是可克隆的。可克隆接口的工作原理类似于用于序列化的可序列化接口# 2 楼答案
您需要实现
Cloneable
并重写clone()
以使用它(使它public
,它是Object
类中的protected
)# 3 楼答案
clone()在默认情况下受保护,请将其覆盖为public