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
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.
You can use Java 8's stream as well to convert any collection to the List. List<Integer> intValuesJava8 = values. stream().
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.
Java List addAll() This method is used to add the elements from a collection to the list. There are two overloaded addAll() methods.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With