Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive arrays in Java collections

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.

like image 588
Elliott Hill Avatar asked Oct 27 '25 01:10

Elliott Hill


2 Answers

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

like image 79
NPE Avatar answered Oct 28 '25 16:10

NPE


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

like image 45
Freak Avatar answered Oct 28 '25 18:10

Freak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!