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
2010-03-18 15:09:39
+1 I'm glad you didn't answer in a comment this time :)
OscarRyz
2010-03-18 15:43:24
+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
2010-03-18 15:10:19
Michael Myers
2010-03-18 15:13:41
Though I agree with mmyers..you can see my answer below for "initializing" a Collection
Omnipresent
2010-03-18 15:36:22
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
2010-03-18 15:25:44
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
2010-03-18 15:34:08
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
2010-09-29 14:34:03