I am not able to figure out why ArrayList<int> is not allowed but ArrayList<int[]> is allowed.
I was under the impression that primitive data types are not allowed in Collections, so why is this legit?
An ArrayList contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int).
ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
ArrayList<Integer> numbers = new ArrayList<>(Arrays. asList(1, 2, 3, 4, 5, 6)); This is how you declare an ArrayList of Integer values. You can do the same to create an ArrayList with String objects as well, e.g.
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
An array
in Java is an object. In Java, we can create arrays by using new
operator and we know that every object is created using new operator. Hence we can say that array
is also an object.
Collection only works on anything which is Object
. int
is the primitive datatype and int[]
is the Object.
That is the reason ArrayList<int>
is not allowed but ArrayList<int[]>
is allowed.
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