int
is primitive type in java. Why is int[]
usable as a generic type?
I can write code like this and compile it.
List<int[]> test = new ArrayList<>();
int
is primitive type in java. Why is int[]
usable as a generic type?
I can write code like this and compile it.
List<int[]> test = new ArrayList<>();
Indeed int is a primitive however an array of integers, int[], isn't.
Java Docs define an array as,
An array is a container object that holds a fixed number of values of a single type.
As you can see an array is an object with class hierarchy as following,
java.lang.Object
java.util.Arrays
So arrays in java are basically objects of type java.util.Arrays. The same class also provides all the good operations you can perform on Arrays.
Back to your question, you're right, Java doesn't allow passing primitives as type parameter when you're using generics.
You cannot do this,
List<int> test = new ArrayList<int>();
However you can do generics with Integer class just fine,
List<Integer> test = new ArrayList<Integer>();
The reasons for not allowing primitives are discussed here on stackoverflow.
One might think, Java does support autoboxing so why not simply autobox primitives to their equivalent classes. Well that is a design choice. Primitives are efficient and cost less memory. Designers probably rightly decided to not assume autoboxing would serve equivalent efficiency.