-1

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<>();
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
HongYi
  • 33
  • 4

1 Answers1

3

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.

Abdullah Leghari
  • 2,332
  • 3
  • 24
  • 40
  • 1
    A more fitting cite would be the [JLS](https://docs.oracle.com/javase/specs/jls/se16/html/jls-10.html): "*In the Java programming language, arrays are objects ...*" – Turing85 May 05 '21 at 19:47
  • @Turing85 yes, thanks. – Abdullah Leghari May 05 '21 at 19:48
  • 2
    *"Arrays in java are basically objects of type java.util.Arrays"* -- I don't think that is correct. `Arrays` is mostly a utility class containing `static` methods that can be used to operate on arrays. It is not the basis for an array type. For example, you don't say `myArray.sort()`, you say `Arrays.sort(myArray)`. – Robert Harvey May 05 '21 at 19:50