Elliott Hill
Elliott Hill

Reputation: 961

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.

Upvotes: 4

Views: 3770

Answers (2)

Freak
Freak

Reputation: 6873

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

Upvotes: 1

NPE
NPE

Reputation: 500307

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

Upvotes: 3

Related Questions