简体   繁体   English

如何转换ArrayList <subClass> 到ArrayList <super> 在java中

[英]How to convert ArrayList<subClass> to ArrayList<super> in java

I hava a method setData(ArrayList<super> list) , so anyone who want set data can have their own entity, just need to extends from super class. 我有一个方法setData(ArrayList<super> list) ,所以任何想要设置数据的人都可以拥有自己的实体,只需要从超类扩展即可。 but when they call setData , how they convert ArrayList to ArrayList? 但是当他们调用setData ,他们如何将ArrayList转换为ArrayList?

Now i use setData(new ArrayList(list)), but it's not a good solution. 现在我使用setData(new ArrayList(list)),但这不是一个好的解决方案。

Anyone can tell me how to convert or another solution can avoid the problem. 任何人都可以告诉我如何转换或其他解决方案可以避免这个问题。 Very appreciated! 非常感激!

It depends on what you want to do with the list afterwards. 这取决于你之后要对列表做什么。 If you're just going to read from it, you can declare your method like this: 如果你只是想从中读取,你可以像这样声明你的方法:

setData(ArrayList<? extends SuperType> list)

You can't add anything to that list, though, because you won't know what ? 但是,你不能在该列表中添加任何内容,因为你不知道什么? is. 是。 Another option is to create a copy when calling your method: 另一种选择是在调用方法时创建副本:

List<SubType> subtypeList = ...;
setData(new ArrayList<SuperType>(subtypeList));

Instead of coding 而不是编码

setData(new ArrayList(list));

you could simply use 你可以简单地使用

setData((ArrayList<super>)((Object)list));

Casting list to Object first and then to ArrayList will force the compiler to accept the method invocation. 首先将对象转换为Object然后再转换为ArrayList将强制编译器接受方法调用。 As an added bonus, you don't suffer the performance expense of creating a new array list. 作为额外的奖励,您不会因创建新阵列列表而遭受性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM