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 not be used for primitive types, like int, char, etc.
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.
Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. We will discuss how we can use the Object class to create an ArrayList.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With