![](/img/trans.png)
[英]List<Integer> to List<Long> conversion in Java 11 using Streams
[英]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;
}
上面的代码无法编译
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());
}
以上代码编译成功,运行成功
为什么?
您不能将List<Integer>
转换为List<BigInteger>
。 相反,您必须将每个Integer
映射到新List
的BigInteger
。 在 Java 8+ 中,最简单的方法是使用stream()
和map
函数。 喜欢,
List<BigInteger> coverList = list.stream()
.map(i -> BigInteger.valueOf(i))
.collect(Collectors.toList());
至于为什么第二个例子有效, 类型擦除导致所有泛型类型在运行时都是Object
。 请注意,它还添加了桥接方法; 因此,一旦您访问List
的值,您当前的代码将在运行时失败。
例如,
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);
输出
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.