Hello, 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
Hello, 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
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);
Casting never needs a new
:
Collection<T> collection = myList;
You don't even make the cast explicit, because Collection
is a super-type of List
, so it will work just like this.
Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.
First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?
If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).
HTH