Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<int> vs ArrayList<int[]>?

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?

like image 480
ace Avatar asked Apr 05 '19 06:04

ace


People also ask

What is ArrayList int in Java?

An ArrayList contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int).

Can you do ArrayList int?

ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.

How do you declare an int ArrayList in Java?

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.

What is the difference between ArrayList and ArrayList <?> In Java?

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.


1 Answers

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.

like image 135
Khalid Shah Avatar answered Oct 20 '22 09:10

Khalid Shah