简体   繁体   中英

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.

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.

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM