简体   繁体   English

Java列表<Integer>转换为列表<BigInteger>问题?

[英]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> .您不能将List<Integer>转换为List<BigInteger> Instead, you have to map each Integer to a BigInteger in a new List .相反,您必须将每个Integer映射到新ListBigInteger The easiest way, in Java 8+, is to use a stream() and the map function.在 Java 8+ 中,最简单的方法是使用stream()map函数。 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.至于为什么第二个例子有效, 类型擦除导致所有泛型类型在运行时都是Object 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 .因此,一旦您访问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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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