0
ArrayList<int> list1 = new ArrayList<int>(); // Error
ArrayList<int[]> list2 = new ArrayList<int[]>(); // Works fine

Generics do not work for primitive types but work fine with Array of primitives. Why?

Follow up:

The only reason I can think of it is because the Array is an object so generics work with them. But if that is so then why couldn't a primitive int array be autoboxed to corresponding Integer wrapper class automatically?

Integer arr = new int[5]; // Error   
Integer[] arr = new int[5]; // Error 
Integer a = 5; // Works fine (autoboxing)

If someone could shed some light on this would be highly appreciated or if I am missing something of how it's represented internally. Thanks.

Surya Saini
  • 1
  • 1
  • 2
  • 1
    When you know that an `int[]` is in itself an Object type, why would expect Autoboxing to happen here? Why do you expect Autoboxing can convert from one Object sub-type to another Object sub-type? – Tom Jun 21 '21 at 11:12
  • Your follow-up doesn't really change the fact that this has been answered before. Also, autoboxing converts *values*, not *types. So if you argue that `List` should just be "autoboxed" to `List` then you've just created an alias for the later that hides what's actually happening. – Joachim Sauer Jun 21 '21 at 11:16
  • Auto(un)boxing is IMHO done by the compiler. The code `Integer a = 5` is treated like `Integer a = new Integer(5)`. But converting an array would require a loop that (un)boxes every single value into a new array. And this would be too much magic to be done silently. – Dietmar Höhmann Jun 21 '21 at 11:18
  • 1
    Since int is not an Object, but a primitive type, so it can't be passed, whereas int[] is an Object itself, so it will go as a single Object element for the generic and not multiple Integer[] objects which I was confused with. The second associated answer clears it all. Thanks @Tom – Surya Saini Jun 21 '21 at 11:45

0 Answers0