Reputation: 1075
I want to declare an ArrayList
of type int
.
Why does the following give me an error:
ArrayList<int> list1 = new ArrayList<int>();
But the following works:
ArrayList<Integer> list1 = new ArrayList<Integer>();
?
Upvotes: 45
Views: 65245
Reputation: 59
int
is a primitive
. It is not a Object
.
Refer this link for further details.
Upvotes: 0
Reputation: 1
int is not an Object and hence if list type is int, implementations of the list cannot be done.
Upvotes: 0
Reputation: 3483
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
Upvotes: 1
Reputation: 1
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
Upvotes: 0
Reputation: 3341
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
Upvotes: 41
Reputation: 1170
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
.
Upvotes: 12
Reputation: 272772
Because int
is a primitive type. Only reference types can be used as generic parameters.
Upvotes: 14