0

I've got two pieces of code, in both the main focus is the method Arrays.asList(T... a).
In the first of them I input an Integer[], in the second I input an int[] , and - this is the part that confuses me, in the two cases, the resulting List<...> is different:

Integer[] arrayBoxed = new Integer[10];
List<Integer> list = Arrays.asList(arrayBoxed);

It's pretty short, and none of the values in arrayBoxed are set, but it works, and produces an List<Integer>.

int[] array = new int[10];
List<int[]> list = Arrays.asList(array);

In this case, for some reason, I get a List<int[]>, which is a pretty pathological construct.

Why is that?

The problem is, that given the similar input into Arrays.asList, I'd expect both of the functions to output the same (both code pieces are fully functional). However, one time the method returns List<Integer>, the other time List<int[]>.

Sudix
  • 353
  • 2
  • 13
  • Here some informations that may be useful for your research -> https://stackoverflow.com/questions/18845289/int-and-integer-arrays-what-is-the-difference – Leviand Aug 30 '18 at 08:33
  • What do you expect to get? – Nicholas K Aug 30 '18 at 08:33
  • List list = Arrays.asList(arrayBoxed); here, you are making a list of elements with type Integer. List list = Arrays.asList(array); here, you declare a list of elements with type 'array of int' – Stultuske Aug 30 '18 at 08:34
  • 2
    `T` can't represent primitive type so in case of `T...` for `in[]` `T` can't become `int` and closest available non-primitive type is array itself. So `List` becomes `List`. – Pshemo Aug 30 '18 at 08:34
  • Take a look at duplicate, especially this answer: https://stackoverflow.com/a/1467940 – Pshemo Aug 30 '18 at 08:40
  • One difference : Basically int is primitive type. and Integer is a wrapper class. when you are declaring variable with int, you can not assign null value to it. But with integer , you can assign null value to it. This difference mostly helps in database when you want to store null values in column from java. – YLG Aug 30 '18 at 08:45

1 Answers1

3

Arrays.asList takes an array of reference types, not primitive types.

So, when you call Arrays.asList(int[]), the reference type taken is int[] (the array type), and that's why the result is List<int[]>.

Integer is a reference type, which explains why List<Integer> is the return type.

ernest_k
  • 39,584
  • 5
  • 45
  • 86