Java 将列表转换为集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2476732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cast a List to a Collection
提问by Mercer
i have some pb. I want to cast a List to Collection in java
我有一些铅。我想在java中将列表转换为集合
Collection<T> collection = new Collection<T>(mylList);
but i have this error
但我有这个错误
Can not instantiate the type Collection
无法实例化类型 Collection
采纳答案by Jon Skeet
List<T>
already implements Collection<T>
- why would you need to create a new one?
List<T>
已经实现Collection<T>
- 为什么你需要创建一个新的?
Collection<T> collection = myList;
The error message is absolutely right - you can't directly instantiate an interface. If you want to create a copyof the existing list, you could use something like:
错误信息是绝对正确的——你不能直接实例化一个接口。如果要创建现有列表的副本,可以使用以下内容:
Collection<T> collection = new ArrayList<T>(myList);
回答by Joachim Sauer
Casting never needs a new
:
铸造永远不需要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.
你甚至不明确强制转换,因为它Collection
是 的超类型List
,所以它会像这样工作。
回答by Mikezx6r
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.
不知道你的代码,回答你的问题有点困难,但根据这里的所有信息,我相信问题是你试图使用 Collections.sort 传递定义为 Collection 的对象,而 sort 不支持那。
First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?
第一个问题。为什么客户端的定义如此笼统?为什么不是 List、Map、Set 或更具体的东西?
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).
如果 client 被定义为 List、Map 或 Set,则不会出现此问题,因为这样您就可以直接使用 Collections.sort(client)。
HTH
HTH
回答by SharpLu
There have multiple solusions to convert list to a collection
有多种解决方案可以将列表转换为集合
Solution 1
解决方案1
List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;
Solution 2
解决方案2
private static final Collection<String> c = new ArrayList<String>(
Arrays.asList("a", "b", "c"));
Solution 3
解决方案3
private static final Collection<Contact> = new ArrayList<Contact>(
Arrays.asList(new Contact("text1", "name1")
new Contact("text2", "name2")));
Solution 4
解决方案4
List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);
回答by Armando
First Collection is class Interface and you can not instantiate. Collection API
第一个集合是类接口,你不能实例化。集合API
List Ver APiis also an interface class.
List Ver APi也是一个接口类。
It may be so
可能是这样
List list = Collections.synchronizedList(new ArrayList(...));
ver enter link description here
Collection collection= Collections.synchronizedList(new ArrayList(...));