简体   繁体   中英

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

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM