[英]Java autoboxing and unboxing
I am trying to convert and array ints to a List however every time I try I get a compilation error. 我正在尝试将int转换和数组化为List,但是每次尝试都会出现编译错误。
List<Integer> integers = toList(draw.getToto6From49().getFirstRound());
// getFirstRound() returns int[] ;
and here is my to toList
method 这是我的
toList
方法
public class ArraysUtil {
public static <T> List<T> toList(T[] ts) {
List<T> ts1 = new ArrayList<>();
Collections.addAll(ts1, ts);
return ts1;
}
}
java: method toList in class com.totoplay.util.ArraysUtil cannot be applied to given types; java:com.totoplay.util.ArraysUtil类中的toList方法不能应用于给定类型;
required: T[]
found: int[]
reason: inferred type does not conform to declared bound(s)
inferred: int
bound(s): java.lang.Object
Yes, you can't do that, basically. 是的,您基本上不能这样做。 You're expecting to be able to call
toList
with a type argument of int
, and Java doesn't allow primitives to be used as type arguments. 您期望能够使用类型参数
int
调用toList
,并且Java不允许toList
语用作类型参数。 You basically need a different method for each primitive you want to handle like this, eg 对于每个要处理的原语,基本上都需要一个不同的方法,例如
public static List<Integer> toList(int[] ts) {
List<Integer> list = new ArrayList<>(ts.length);
for (int i in ts) {
list.add(i);
}
}
At least, that's the case in Java 7 and before. 至少在Java 7和更低版本中就是这种情况。 In Java 8 it's slightly simpler:
在Java 8中,它稍微简单一些:
int[] array = { 1, 2, 3 };
IntStream stream = Arrays.stream(array);
List<Integer> list = stream.boxed().collect(Collectors.toList());
It's because primitive types don't play nicely with generics. 这是因为基本类型不能很好地与泛型一起使用。 All generics need to be treatable as objects, and primitives can't be.
所有泛型都必须被视为对象,而原语则不能。 More Detail
更多详情
In Java 8 you can do this: 在Java 8中,您可以执行以下操作:
List<Integer> list = new ArrayList<>();
list.add(101); // autoboxing will work
int aValue = list.get(0); // autounboxing will work, too
Specifying the Integer type in angle brackets (< Integer >), while creating the List object, tells the compiler that the List will hold object of only Integer type.
在创建List对象时,在尖括号中指定Integer类型(<Integer>)会告诉编译器List将仅保留Integer类型的对象。 This gives the compiler freedom to wrap and unwrap your primitive int values while you work with the List object
这使编译器可以在使用List对象时自由包装和解开原始int值。
from the book: Beginning Java 8 Fundamentals
书中的内容:入门Java 8基础
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.