我有一个 ArrayList<String>
,希望返回它的一个副本。 ArrayList
有一个克隆方法,其签名如下:
public Object clone()
调用这个方法之后,我该如何将返回的对象转换回
ArrayList<String>
?我有一个 ArrayList<String>
,希望返回它的一个副本。 ArrayList
有一个克隆方法,其签名如下:
public Object clone()
ArrayList<String>
?ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();
我不是Java专家,但我有同样的问题并尝试通过这种方法解决(假设T具有拷贝构造函数)。
public static <T extends Object> List<T> clone(List<T> list) {
try {
List<T> c = list.getClass().newInstance();
for(T t: list) {
T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
c.add(copy);
}
return c;
} catch(Exception e) {
throw new RuntimeException("List cloning unsupported",e);
}
}
List
实现类具有公共的无参构造函数。例如,由 Array.asList
、List.of
或 List.subList
返回的 List
可能没有这个构造函数。 - Tom Hawtin - tackline