将列表转换为集合
我有一些pb。我想在 java 中将列表转换为集合
Collection<T> collection = new Collection<T>(mylList);
,但出现此错误
无法实例化类型 Collection
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
List
已经实现了Collection
- 为什么您需要创建一个新的?错误消息是绝对正确的 - 你不能直接实例化接口。如果您想创建现有列表的副本,您可以使用类似以下内容的内容:
List<T>
already implementsCollection<T>
- why would you need to create a new one?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:
转换永远不需要
new
:您甚至不需要显式转换,因为
Collection
是List
的超类型,因此它会就像这样工作。Casting never needs a
new
:You don't even make the cast explicit, because
Collection
is a super-type ofList
, so it will work just like this.将列表转换为集合有多种解决方案
解决方案 1
解决方案 2
解决方案 3
解决方案 4
There have multiple solusions to convert list to a collection
Solution 1
Solution 2
Solution 3
Solution 4
不知道你的代码,很难回答你的问题,但根据这里的所有信息,我相信问题是你正在尝试使用 Collections.sort 传入定义为 Collection 的对象,而排序不支持那。
第一个问题。为什么客户端的定义如此笼统?为什么不是列表、地图、集合或者更具体的东西?
如果 client 被定义为 List、Map 或 Set,则不会出现此问题,因为这样您就可以直接使用 Collections.sort(client)。
华泰
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
第一个集合是类接口,您无法实例化。 集合 API
列表 Ver APi 也是一个接口类。
可能是这样
在此处输入链接描述
First Collection is class Interface and you can not instantiate. Collection API
List Ver APi is also an interface class.
It may be so
ver enter link description here