Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast a List to a Collection

i have some pb. I want to cast a List to Collection in java

Collection<T> collection = new Collection<T>(mylList);  

but i have this error

Can not instantiate the type Collection

like image 710
Mercer Avatar asked Mar 19 '10 11:03

Mercer


People also ask

Can I cast a collection to a list?

Use addAll to Convert Collection Into List in Java. addAll() is a method provided in the collections framework that we can use to convert a collection to a list. The elements from the collection can be specified one by one or as an array.

Can we cast collection to list Java?

You can use Java 8's stream as well to convert any collection to the List. List<Integer> intValuesJava8 = values. stream().

How will you convert a list to a Set?

Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java. We simply create an list. We traverse the given set and one by one add elements to the list. // Set to array using addAll() method.

How do I add a collection to a list in Java?

Java List addAll() This method is used to add the elements from a collection to the list. There are two overloaded addAll() methods.


1 Answers

List<T> already implements Collection<T> - why would you need to create a new one?

Collection<T> collection = myList; 

The error message is absolutely right - you can't directly instantiate an interface. If you want to create a copy of the existing list, you could use something like:

Collection<T> collection = new ArrayList<T>(myList); 
like image 147
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet