[英]Convert ArrayList<String> to ArrayList<Object>
If type B
can be generalised to type A
, how do I convert a List<B>
to a List<A>
? 如果类型B
可以推广到类型A
,如何将List<B>
转换为List<A>
? Do I need a loop like: 我需要一个循环:
List<A> newList=new ArrayList<A>();
for(B t:oldList) newList.add(t);
Edit: I don't know the word for it, but I mean to say an object of type B
can be casted to an object of type A
(like B implements A
). 编辑:我不知道它的含义,但我的意思是说类型B
的对象可以被转换为类型A
的对象(如B implements A
)。
Edit2: It appears that the constructor also works: Edit2:似乎构造函数也有效:
List<A> newList=new ArrayList<A>(oldList);
However, I wanted a more efficient approach rather than just copying the list. 但是,我想要一种更有效的方法,而不仅仅是复制列表。
You shouldn't since List<B>
means that it will contain only elements of type B or subtypes. 你不应该因为List<B>
意味着它只包含B类或子类型的元素。 List<A>
would allow you to add elements of type A as well, which might be dangerous. List<A>
允许您添加类型A的元素,这可能是危险的。 Hence you shouldn't cast a List<B>
into a List<A>
. 因此,您不应将List<B>
List<A>
转换为List<A>
。
If you create a new List<A>
and put all elements of List<B>
into it (eg using a loop possibly wrapped in a method) it's ok. 如果您创建一个新的List<A>
并将List<B>
所有元素放入其中(例如使用可能包含在方法中的循环),那就没问题。
One simple way to fill a new list would be the addAll()
method, eg 填充新列表的一种简单方法是addAll()
方法,例如
List<A> aList = ...;
List<B> bList = ...;
aList.addAll( bList );
As you stated in comments , If your Class B implements Class A
, the below code is perfectly alight. 正如您在评论中所述 ,如果您的Class B implements Class A
,则以下代码完全正常。
newList.addAll(listofBs);
Since every B
is an A
, you are allowed to do that. 由于每个B
都是A
,因此您可以这样做。
And yes you need not to have a loop. 是的,你不需要循环。
Generics does not allow you to directly up cast collection objects. 泛型不允许您直接向上转换集合对象。
You can do couple of things: 你可以做几件事:
List<B> oldList = new List<B>();
List<? super B> upcastedList = oldList; // No new object created.
If you need to cast the list to a specific type (say A), then you have no option than to loop every element and add it to new list (as you have specified in the question). 如果您需要将列表强制转换为特定类型(例如A),那么除了循环每个元素并将其添加到新列表(如您在问题中指定的那样)之外,您别无选择。
它可以在创建过程中添加
List<A> newList = new ArrayList<A>(oldList);
If you are OK with listA being unmodifiable, here's another possible answer (using Ankur's hint): 如果你可以使用listA不可修改,那么这是另一个可能的答案(使用Ankur的提示):
List<B> listB=new ArrayList<B>();
List<A> listA=Collections.unmodifiableList((List<? extends A>)listB);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.