i have some pb. I want to cast a List to Coll开发者_开发知识库ection 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.
There have multiple solusions to convert list to a collection
Solution 1
List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;
Solution 2
private static final Collection<String> c = new ArrayList<String>(
Arrays.asList("a", "b", "c"));
Solution 3
private static final Collection<Contact> = new ArrayList<Contact>(
Arrays.asList(new Contact("text1", "name1")
new Contact("text2", "name2")));
Solution 4
List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);
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
First Collection is class Interface and you can not instantiate. Collection API
List Ver APi is also an interface class.
It may be so
List list = Collections.synchronizedList(new ArrayList(...));
ver enter link description here
Collection collection= Collections.synchronizedList(new ArrayList(...));
精彩评论