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 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.
Generics only work for reference type (anything that is an Object).
Primitive int isn't a reference type.
int[] is, as any array is also an Object.
The proper way to deal with multiple int values is to either use just int[] (not putting them into lists), or to use List<Integer>. Which one to pick really depends on your exact use case.
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.
In Java, there is a class for every array type, so there’s a class for int[] and similarly for float, double etc. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable. All methods of class Object may be invoked on an array. This can be checked from below code :
public class Test {
public static void main(String[] args)
{
System.out.println(args instanceof Object);
int[] arr = new int[2];
System.out.println(arr instanceof Object);
}
}
Output : True True
The diamond operator used in ArrayList initialisation specifies a generic type. A generic type is a generic class or interface that is parameterised over types.
You can go through the source code for ArrayList here: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/java/util/ArrayList.java
You can see that the type of elementData in parameterised constructor is Object. A primitive is a data type which is not an object :
private transient Object[] elementData;
So as int is primitive data type in java it cannot be used as Generic type where as int[] , that has direct superclass Object, can be.
You can read more about it here: https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
System.out.println(args instanceof Object[]); would also be true, even though Object[] is not a superclass of String[]. (It is a supertype, though).
int[]is a reference type (i.e. you can assign anint[]to anObjectvariable).Object o = new int[10];