I want to declare an ArrayList
of type int
.
Why does the following give me an error:
ArrayList list1 = new Array
Because int
is a primitive type. Only reference types can be used as generic parameters.
ArrayList
can only reference types, not primitives. Integer
is a class, not a primitive.
When you declare ArrayList<Integer> list1 = new ArrayList<Integer>()
, you're creating an ArrayList
which will store the Integer
type, not the int
primitive.
If you want to read about the difference between primitive and reference types, check out http://pages.cs.wisc.edu/~hasti/cs302/examples/primitiveVsRef.html
int is not an Object and hence if list type is int, implementations of the list cannot be done.
All the answers above answer why but the root of this question is frequent auto boxing and unboxing of the primitive data types. This problem is already solved by IntBuffer or ChadBuffer or you name the primitive type it's already there in the nio folder. Next time if you want to use primitive ArrayList don't use List instead use IntBuffer
The short answer is that generics (like ArrayList<Integer>
) do not accept primitive types (int
), only objects (Integer
).
This is because classes like ArrayList
are implemented as using Objects. Since every class inherits from Object, the compiler can just plug in other classes. But primitive types (like int
) do not inherit from Object, for they are not classes. So, Sun/Oracle made the Integer
class to help with this.
So, in short: int
is not an Object
.
int is a primitive data type but Integer is a class so an arrayList array can only take reference types as its parameter not primitive type