Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

In my application I want to convert an ArrayList of Integer objects into an ArrayList of Long objects. Is it possible?

like image 777
Shajeel Afzal Avatar asked Mar 18 '13 18:03

Shajeel Afzal


2 Answers

Not in a 1 liner.

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

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());
like image 199
Tom Avatar answered Oct 18 '22 03:10

Tom


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>.

List<Long> longList = new ArrayList<Long>();
for(Integer i: intList){
longList.add(i.longValue());
}
like image 26
PermGenError Avatar answered Oct 18 '22 01:10

PermGenError