0

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
Adelin
  • 18,144
  • 26
  • 115
  • 175

3 Answers3

5

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());
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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

Community
  • 1
  • 1
Mshnik
  • 7,032
  • 1
  • 25
  • 38
0

In Java 8 you can do this:

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. This gives the compiler freedom to wrap and unwrap your primitive int values while you work with the List object

from the book: Beginning Java 8 Fundamentals

Community
  • 1
  • 1
Robert
  • 10,403
  • 14
  • 67
  • 117