是否可以实现此方法?
public <T> Set<T> cloneSet(Set<T> original);
生成的Set 必须与原始Set的类型相同(例如,如果original是TreeSet,则生成的Set也是TreeSet。
答案 0 :(得分:0)
您可以使用反射。见这个例子:
public class CloneTest {
public static <T> Set<T> clone(Set<T> set) {
try {
Set<T> cloned = set.getClass().newInstance();
cloned.addAll(set);
return cloned;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
Set<String> test = new TreeSet<>();
test.add("asd");
printClone(clone(test));
printClone(clone(new HashSet<>(test)));
}
public static void printClone(Set<?> set) {
System.out.println(set.getClass().getSimpleName());
set.forEach(System.out::println);
}
}
这将打印:
TreeSet
asd
HashSet
asd
它使用类信息来创建一个新实例。鉴于我们知道它是一个集合,我们可以调用addAll来添加所有元素。虽然元素没有克隆,但它们是相同的参考。
这是有效的,因为集合上有一个默认构造函数。我相信如果你有一个非空的构造函数,newInstance
方法可能会失败。
这是一个有趣的小例子,但我不会在制作中使用它:)
Artur