在我的应用程序中,我想将一个包含整数对象的ArrayList转换为一个包含长整型对象的ArrayList。这是否可能?
不是一行代码。
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());
}
// 或者你可以在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());
ArrayList<Integer>
不是 ArrayList<Long>
的子类型,因此转换会失败。
因此,唯一的方法是遍历您的 List<Integer>
并将其添加到 List<Long>
中。List<Long> longList = new ArrayList<Long>();
for(Integer i: intList){
longList.add(i.longValue());
}
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
}
完成了....
longList.add((long)obj);
或者其他解决方案都可以使用。 - T Tse