Java 将集合转换为列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2470856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Collection to List
提问by Mercer
I would like to ask: how do you convert a Collection
to a List
in Java?
请问:在Java中如何将a转换Collection
为a List
?
采纳答案by Uri
If you have already created an instance of your List subtype (e.g., ArrayList, LinkedList), you could use the addAll method.
如果您已经创建了 List 子类型的实例(例如,ArrayList、LinkedList),则可以使用 addAll 方法。
e.g.,
例如,
l.addAll(myCollection)
Many list subtypes can also take the source collection in their constructor.
许多列表子类型也可以在其构造函数中使用源集合。
回答by Michael Myers
Collection<MyObjectType> myCollection = ...;
List<MyObjectType> list = new ArrayList<MyObjectType>(myCollection);
See the Collections trailin the Java tutorials.
回答by bmargulies
Make a new list, and call addAll
with the Collection.
创建一个新列表,并addAll
使用 Collection调用。
回答by Cshah
you can use either of the 2 solutions .. but think about whether it is necessary to clone your collections, since both the collections will contain the same object references
您可以使用这两种解决方案中的任何一种..但请考虑是否有必要克隆您的集合,因为这两个集合都将包含相同的对象引用
回答by Omnipresent
Collection
and List
are interfaces. You can take any Implementation of the List
interface: ArrayList LinkedList
and just cast it back to a Collection
because it is at the Top
Collection
并且List
是接口。您可以采用List
接口的任何实现:ArrayList LinkedList
并将其强制转换回 aCollection
因为它位于顶部
Example below shows casting from ArrayList
下面的示例显示了从 ArrayList
public static void main (String args[]) {
Collection c = getCollection();
List myList = (ArrayList) c;
}
public static Collection getCollection()
{
Collection c = new ArrayList();
c.add("Apple");
c.add("Oranges");
return c;
}
回答by Sandeep Bhardwaj
List list;
if (collection instanceof List)
{
list = (List)collection;
}
else
{
list = new ArrayList(collection);
}
回答by Vijay Kumar Rajput
Thanks for Sandeep putting it- Just added a null check to avoid NullPointerException in else statement.
感谢 Sandeep 把它 - 刚刚添加了一个空检查以避免在 else 语句中出现 NullPointerException。
if(collection==null){
return Collections.emptyList();
}
List list;
if (collection instanceof List){
list = (List)collection;
}else{
list = new ArrayList(collection);
}