views:

164

answers:

6

Hello, I want to say how to convert a Collection to a List in Java

+9  A: 
Collection<MyObjectType> myCollection = ...;
List<MyObjectType> list = new ArrayList<MyObjectType>(myCollection);

See the Collections trail in the Java tutorials.

Michael Myers
+1 I'm glad you didn't answer in a comment this time :)
OscarRyz
A: 

Make a new list, and call addAll with the Collection.

bmargulies
+2  A: 

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.

Uri
A: 

How do you initialise a Collection collection ..?

Mercer
Michael Myers
Though I agree with mmyers..you can see my answer below for "initializing" a Collection
Omnipresent
A: 

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

Cshah
A: 

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;
}
Omnipresent
why -1? explain?
Omnipresent
I suspect you were downvoted because _this won't always work_. Sure, when the `Collection`'s implementing class implements `List` (e.g. `ArrayList`, `LinkedList`...), you're fine. But as soon as you try to do something like `Map<Foo,Bar> myMap = new HashMap<Foo,Bar>(); List<Bar> fromMap = (List<Bar>) myMap.values();` everything looks fine at compile time - but when you run it, you get `java.lang.ClassCastException: java.util.HashMap$Values cannot be cast to java.util.List`.
Matt Ball