I am trying to convert and array ints to a List however every time I try I get a compilation error.
List<Integer> integers = toList(draw.getToto6From49().getFirstRound());
// getFirstRound() returns int[] ;
and here is my to toList
method
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;
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. You basically need a different method for each primitive you want to handle like this, e.g.
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. In Java 8 it's slightly simpler:
int[] array = { 1, 2, 3 };
IntStream stream = Arrays.stream(array);
List<Integer> list = stream.boxed().collect(Collectors.toList());
See more on this question at Stackoverflow