如何转换列表<字符串>列出<对象> [英] How to Convert List<String> to List<Object>
问题描述
我想把List
转换成List
.
现有方法之一是返回List
,我想将其转换为List
.除了逐个元素迭代和转换之外,Java 中有没有直接的方法?
One of the existing methods is returning List<String>
and I want to convert it to List<Object>
.
Is there a direct way in Java other then iterating over and converting element by element?
推荐答案
将 List
作为参数传递给新的 ArrayList
的构造函数.
Pass the List<String>
as a parameter to the constructor of a new ArrayList<Object>
.
List<Object> objectList = new ArrayList<Object>(stringList);
任何 Collection
都可以作为参数传递给构造函数,只要它的类型扩展了 ArrayList
的类型,如 String
扩展<代码>对象代码>.构造函数接受一个Collection
,但List
是Collection
的子接口,所以你可以直接使用List
代码>.
Any Collection
can be passed as an argument to the constructor as long as its type extends the type of the ArrayList
, as String
extends Object
. The constructor takes a Collection
, but List
is a subinterface of Collection
, so you can just use the List<String>
.
这篇关于如何转换列表<字符串>列出<对象>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!