Convert Collection to List [duplicate]
I would like to ask: how do you convert a Collection
to a 开发者_如何转开发List
in Java?
Collection<MyObjectType> myCollection = ...;
List<MyObjectType> list = new ArrayList<MyObjectType>(myCollection);
See the Collections trail in the Java tutorials.
If you have already created an instance of your List subtype (e.g., ArrayList, LinkedList), you could use the addAll method.
e.g.,
l.addAll(myCollection)
Many list subtypes can also take the source collection in their constructor.
List list;
if (collection instanceof List)
{
list = (List)collection;
}
else
{
list = new ArrayList(collection);
}
Make a new list, and call addAll
with the Collection.
Thanks for Sandeep putting it- Just added a null check to avoid NullPointerException in else statement.
if(collection==null){
return Collections.emptyList();
}
List list;
if (collection instanceof List){
list = (List)collection;
}else{
list = new ArrayList(collection);
}
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
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
Example below shows casting from 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;
}
精彩评论