I know that it is impossible to create List<int>
since int is a primitive type. However, I want to know why I can create List<int[]>
. Basically, my question is why it is possible to have Collection<primitive_type_array>
in Java.
Asked
Active
Viewed 1,339 times
7

rgettman
- 176,041
- 30
- 275
- 357

dmitryvinn
- 392
- 3
- 9
-
1Do you mean why can you have List
? It's because int[] is not a primitive type, it's an array of primitive types. – Neil Locketz Mar 11 '16 at 20:12 -
Generics enforce certain rules about what can be used - basically, in your case, no primitives are allowed. An array is not a primitive, it's an `Object`. Even if it is of primitives. – Kon Mar 11 '16 at 20:13
-
I think OP knows the difference between array and primitives. He probably wants to know more about generics. – user3437460 Mar 11 '16 at 20:21
4 Answers
5
According to Java Language Specification
In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

Radu Ionescu
- 3,462
- 5
- 24
- 43
4
Generics can hold anything that is not a primitive type. Arrays are not primitive types so Collection<int[]>
is allowed. See: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html

Neil Locketz
- 4,228
- 1
- 23
- 34
3
An array is an object. Notice how you can call the standard Object methods on it? As well, you initialize it with the new keyword.

Troncoso
- 2,343
- 3
- 33
- 52
-1
Because array is object that hold references to other objects or primitive types in itself. https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html

HuTa
- 168
- 1
- 8