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
Is it possible to convert ArrayList<Integer> into ArrayList<Long>?
提问by Shajeel Afzal
In my application I want to convert an ArrayList
of Integer
objects into an ArrayList
of Long
objects. Is it possible?
在我的应用程序中,我想将一个ArrayList
ofInteger
对象转换为一个ArrayList
ofLong
对象。是否可以?
回答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
回答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....
完毕....