views:

106

answers:

3

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

+4  A: 

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);
Jon Skeet
When i do Collection<T> collection = new ArrayList<T>(myList);after i put my list in my Objectobj.setMyCollection(collection );or in my obj the collection is define Collection not ArrayList so when i want to see the result i have an error
Mercer
@Mercer what is the signature of the method you're calling? A List should work on setMyCollection(Collection collection), but not if it's e.g. setMyCollection(Map collection) :) And if it's setMyCollection(List collection) then you should put something in that's declared a List: List collection = new ArrayList(); (removed generics to shorten it)
extraneon
+2  A: 

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.

Joachim Sauer
when i do this , i have an errorType mismatch: Can not convert List <T> in Collection<T>
Mercer
@Mercer: are you talking about `java.util.List` here? Could you give us some context (how is `<T>` defined, for example)?
Joachim Sauer
@Mercer: Please provide a short but *complete* example then.
Jon Skeet
i do this Collections.sort(new ArrayList<Client>(product.getClient()));but in my obj product i have thispublic void setClient(Collection<Client> produitEvolution) {this.client= client;}public Collection<Client> getClient() {return client;}
Mercer
A: 

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

Mikezx6r