以下是一个使用Java泛型编写的简单工具类示例,该工具类用于执行集合的深拷贝操作:
import java.util.ArrayList;
import java.util.Collection;
public class DeepCopyUtil<T> {
// 泛型方法,用于执行深拷贝
public static <T extends Cloneable> Collection<T> deepCopy(Collection<T> source) {
if (source == null) {
return null;
}
Collection<T> target = new ArrayList<>(source.size());
for (T item : source) {
try {
// 假设T类型的元素都实现了Cloneable接口并提供了正确的clone方法
T clonedItem = (T) item.clone();
target.add(clonedItem);
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Element in collection does not support clone operation", e);
}
}
return target;
}
}
// 使用示例
List<String> originalList = new ArrayList<>();
originalList.add("Hello");
originalList.add("World");
List<String> copiedList = DeepCopyUtil.deepCopy(originalList);
注意:上述代码中的深拷贝实现基于Java的