5

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

One exception though: auto-boxing, e.g. boxing a primitive int into an Integer object. But you're correct about array casts: even with auto-boxing, you cannot cast an int[] into an Integer[].
@MattiasBeulens But that's not casting. That's simply wrapping the value
@VinceEmigh Technically correct, but it looks like a cast so I thought I'd at least mention it.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.