Array of object-object to general array
I am currently reviewing the java.util.ArrayList source code. Now I find a public void secureCapacity (int minCapacity) function that brings an array of objects into a shared array like the code below:
E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
However, when I declare the array to be a specific type, the IDE will show an error.
Object[] arr = new Object[10];
int[] arr1 = (int[]) new Object[arr.length];
Can anyone please tell me about the differences between the two? Many thanks.
source to share
This is because E
(in the source code ArrayList
) denotes some reference type, but not some primitive type.
And that's why you get a compile time error when you try to pass an array of instances Object
to an array of primitives.
If you do this (for example)
Object[] arr = new Object[10];
Integer[] arr1 = (Integer[]) new Object[arr.length];
the error will disappear.
source to share
You can never use a reference type (all, that extends from Object
) to a primitive type ( int
, long
, boolean
, char
etc.).
You also cannot differentiate an array of a reference type, for example Object[]
to an array of a primitive type int[]
.
And primitives cannot stand behind a common parameter.
source to share