Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object array to generic array

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.

like image 786
mychaint Avatar asked Jul 03 '15 08:07

mychaint


1 Answers

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.

like image 184
Konstantin Yovkov Avatar answered Oct 10 '22 08:10

Konstantin Yovkov