When I implement a Collection using generics that holds primitive arrays within Java what is actually stored within the array? Using generics to define collections means that I can only store an Object and if I were to do ArrayList<Integer> I can add an int but this is autoboxed into Integer.
If I were to define ArrayList<int[]> its perfectly legal as arrays are objects. I'm unsure though if what I actually end up with stored in the collection is Integer[] as the compiler performs some transformations and will use autoboxing to add to the array or if I can store int[] and the collection will store the primitive array as the array itself is an object.
ArrayList<int[]> will store arrays of primitives. There will be no autoboxing involved.
In Java, an array of any type -- primitive or not -- is an object and is therefore compatible with generics.
It is even possible to inadvertently end up with a container of int[], as illustrated by this fun question from yesterday: Java containsAll does not return true when given lists
int[] never be boxed to Integer[].Arrays are always reference types, so no boxing is required.
Java always tackle Arrays as a object either it is a primitive array or Object array.
Here is a little detail about arrays of primitives and objects.For further detail please see Arrays of Primitive Values and objects.
I also suggest you to see this question Java: Array of primitive data types does not autobox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With