Home > database >  Java List<Integer> conversion to List<BigInteger> issue?
Java List<Integer> conversion to List<BigInteger> issue?

Time:11-13

public static void main(String[] args) {
   List<Integer> list = new ArrayList<>(2);
   list.add(12);
   list.add(13);

   // can not cast
   List<BigInteger> coverList = (List<BigInteger>)list;
}

The above code fails to compile

public static void main(String[] args) {
   List<Integer> list = new ArrayList<>(2);
   list.add(12);
   list.add(13);

   Map<String, Object> map = new HashMap<>(1);
   map.put("list", list);
   List<BigInteger> coverList = (List<BigInteger>) map.get("list");

   System.out.println(coverList.size());
}

The above code compiles successfully and runs successfully

why?

CodePudding user response:

You can't cast a List<Integer> to a List<BigInteger>. Instead, you have to map each Integer to a BigInteger in a new List. The easiest way, in Java 8 , is to use a stream() and the map function. Like,

List<BigInteger> coverList = list.stream()
        .map(i -> BigInteger.valueOf(i))
        .collect(Collectors.toList());

As for why the second example works, type erasure causes all generic types to be Object at runtime. Be aware, that it also adds a bridge method; so your current code will fail at runtime once you access a value in the List.

For example,

List<Integer> list = new ArrayList<>(2);
list.add(12);
list.add(13);

Map<String, Object> map = new HashMap<>(1);
map.put("list", list);
List<BigInteger> coverList = (List<BigInteger>) map.get("list");
List<BigInteger> coverList2 = list.stream().map(i -> BigInteger.valueOf(i)).collect(Collectors.toList());
System.out.println(coverList.get(0));
BigInteger bi = coverList.get(0);
System.out.println(bi);

Outputs

12
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.math.BigInteger (java.lang.Integer and java.math.BigInteger are in module java.base of loader 'bootstrap')
  •  Tags:  
  • java
  • Related