java 是否可以将 ArrayList<Integer> 转换为 ArrayList<Long>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15484059/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:45:00  来源:igfitidea点击:

Is it possible to convert ArrayList<Integer> into ArrayList<Long>?

javaarraylist

提问by Shajeel Afzal

In my application I want to convert an ArrayListof Integerobjects into an ArrayListof Longobjects. Is it possible?

在我的应用程序中,我想将一个ArrayListofInteger对象转换为一个ArrayListofLong对象。是否可以?

回答by Tom

Not in a 1 liner.

不是 1 班轮。

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
int nInts = ints.size();
List<Long> longs = new ArrayList<Long>(nInts);
for (int i=0;i<nInts;++i) {
    longs.add(ints.get(i).longValue());
}

// Or you can use Lambda expression in Java 8

// 或者你可以在 Java 8 中使用 Lambda 表达式

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
List<Long> longs = ints.stream()
        .mapToLong(Integer::longValue)
        .boxed().collect(Collectors.toList());

回答by PermGenError

No, you can't because, generics are not polymorphic.I.e., ArrayList<Integer>is not a subtype of ArrayList<Long>, thus the cast will fail. Thus, the only way is to Iterate over your List<Integer>and add it in List<Long>.

不,你不能,因为泛型不是多态的。ArrayList<Integer>即,不是 的子类型ArrayList<Long>,因此转换将失败。因此,唯一的方法是迭代您的List<Integer>并将其添加到List<Long>.

List<Long> longList = new ArrayList<Long>();
for(Integer i: intList){
longList.add(i.longValue());
}

回答by rbedger

See herefor an example relating to converting lists. Of course it is possible.

有关转换列表的示例,请参见此处。当然这是可能的。

回答by VishalDevgire

ArrayList<Long> longList = new ArrayList<Long>();

Iterator<Integer> it = intList.iterator();
while(it.hasNext())
{
    Integer obj = it.next();
    longList.add(obj); //will automatically convert Int to Long
}

Done....

完毕....