Search code examples
javagenericsarraylisttypecasting-operator

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.


Solution

  • 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.