[英]Generic LinkedList clone in Java
I want to clone any LinkedList, whether or not it holds things which can be primitive wrappers. 我想克隆任何LinkedList,无论它是否包含可以是原始包装器的东西。 I understand it can be a deep recursive call to get a true deep clone - but I want just one level of cloning. 我知道它可以是一个深度递归调用来获得真正的深度克隆 - 但我只需要一个级别的克隆。 I cannot compile the following code : 我无法编译以下代码:
<T> LinkedList<T> deepCloneOneLevel (final LinkedList<T> input){
if(input != null){
LinkedList<T> clone = new LinkedList<>();
for (T t: input){
clone.add(t.clone()); //error : clone() has protected access
}
return clone;
}
return null;
}
As mentioned in the comments, Java's Cloneable is not a very friendly method to clone an object. 正如评论中所提到的,Java的Cloneable不是克隆对象的非常友好的方法。 So, You might need to define your Cloneable
interface, and make sure 因此,您可能需要定义Cloneable
接口,并确保
interface MyClone<T>{
T clone();
}
And use that in your code 并在您的代码中使用它
<T extends MyClone<? super T>> LinkedList<T> deepCloneOneLevel (final LinkedList<T> input){
if(input != null){
LinkedList<T> clone = new LinkedList<>();
for (T t: input){
clone.add(t.clone());
}
return clone;
}
return null;
}
And implementations of MyClone
know if a shallow copy is enough or a deep copy is required 并且MyClone
实现知道浅拷贝是否足够或需要深拷贝
But what if the type doesn't implement MyClone
? 但是,如果该类型没有实现MyClone
怎么MyClone
? Good question. 好问题。 We can add an overload that takes a clone
"factory". 我们可以添加一个clone
“工厂”的重载。
<T> LinkedList<T> deepCloneOneLevel (final LinkedList<T> input, Function<T,T> factory){
if(input != null){
LinkedList<T> clone = new LinkedList<>();
for (T t: input){
clone.add(factory.apply(t));
}
return clone;
}
return null;
}
If your platform doesn't have Function
yet, you can easily write your own, or use Guava's one. 如果您的平台还没有Function
,您可以轻松编写自己的功能,或使用Guava的功能。
Since clone()
method is a big mess in java world, one solution may be to use apache commons SerializationUtils. 由于clone()
方法在java世界中是一个很大的混乱,一种解决方案可能是使用apache commons SerializationUtils。 It uses serialization to copy objects and as a result is slow. 它使用序列化来复制对象,因此速度很慢。 What is worse you'll have troubles if your class contains fields that do not support serialization. 更糟糕的是,如果您的类包含不支持序列化的字段,您将遇到麻烦。 Here's an example: 这是一个例子:
<T extends Serializable> LinkedList<T> deepCloneOneLevel (final LinkedList<T> input) {
if (input != null) {
LinkedList<T> clone = new LinkedList<>();
for (T t : input){
clone.add(SerializationUtils.clone(t));
}
return clone;
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.