如何从Enumeration<? extends T>构造List<T>
我发现的最好的方法就是这样
Enumeration<? extends T> toBeConverted;
List<T> = new ArrayList<>(Collections.list(toBeConverted));但这会创建一个两个List (一个在Collections.list方法中,另一个在ArrayList的构造函数中)。有什么方法可以避免这种临时拷贝吗?
(其他解决方案是:
List<T> list = new ArrayList<T>;
while (toBeConverted.hasMoreElements) { list.add(toBeConverted.nextElement()); }但我认为这太冗长了.如果可能的话,我想要一个带有构造函数的解决方案)
发布于 2014-10-20 19:00:01
方法Collections.list生成新的ArrayList。
public static <T> ArrayList<T> list(Enumeration<T> e) {
ArrayList<T> l = new ArrayList<>();
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}您可以只调用Collections.list方法而不调用构造函数。
Enumeration<? extends T> toBeConverted;
List<T> = (List<T>) Collections.list(toBeConverted);https://stackoverflow.com/questions/26463761
复制相似问题