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>(); ?
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
ArrayList<Integer> list1=new ArrayList(); works too.Because int is a primitive type. Only reference types can be used as generic parameters.
new ArrayList().add(5). But the OP is asking about the error wrt that particular line of code...Integer not an int value.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.
ArrayList<int[]>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
int is a primitive. It is not a Object.
Refer this link for further details.
intisn't an object in the same context theIntegerisTIntArrayListif you want something which wrapsint[]intis primitive datatype we can use wrapper class inArrayList