简体   繁体   中英

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.

   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, 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. 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());

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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