Reputation: 105
Currently, I am viewing the source code of java.util.ArrayList. Now I find the function public void ensureCapacity(int minCapacity) casts an object array to a generic array, just like code below:
E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
However, when I declare the array to a specific type, IDE will show an error.
Object[] arr = new Object[10];
int[] arr1 = (int[]) new Object[arr.length];
Any one is able to tell me the differences between them? Thanks a lot.
Upvotes: 5
Views: 4216
Reputation: 3052
int
is not Object
, but it's primitive.
Use Integer
and it will work.
Object[] arr = new Object[10];
Integer[] arr1 = (Integer[]) new Object[arr.length];
Upvotes: 2
Reputation: 62864
It's because E
(in the source code of ArrayList
) stands for some reference type, but not for some primitive type.
And that's why you get a compile-time error when trying to cast an array of Object
instances to an array of primitives.
If you do (for example)
Object[] arr = new Object[10];
Integer[] arr1 = (Integer[]) new Object[arr.length];
the error will be gone.
Upvotes: 4
Reputation: 31279
You can never cast a reference type (anything that extends from Object
) to a primitive type (int
, long
, boolean
, char
, etc.).
You can also not cast an array of a reference type like Object[]
to an array of a primitive type like int[]
.
And primitives cannot stand in for a generic parameter.
Upvotes: 3