3

See the code

Integer[] array = (Integer[]) new Object[size];

this obviously do not works, I understand perfectly.

but why with generics works?

T[] array = (T[]) new Object[size];

if T is Integer class, after that line the array will be Object[] type, but why cast is possible? does not throw ClassCastException?

3
  • docs.oracle.com/javase/tutorial/java/generics/erasure.html Commented Sep 5, 2014 at 20:04
  • 6
    As a rule of thumb, generics and arrays don't mix well. Commented Sep 5, 2014 at 20:06
  • Avoid generics and arrays. Avoid casting arrays. This is a an area of the language that is somewhat unsafe - it's very easy to end up with an ArrayStoreException at runtime. Commented Sep 5, 2014 at 20:13

2 Answers 2

3

but why with generics works?

It's because the generic version is type-erased and compiled to following -

Object[] array = new Object[size];
Sign up to request clarification or add additional context in comments.

3 Comments

SomeClass<T extends Comparable<T>> { T[] array; } will be translated to Comparable<Object>[] array; right?
Just compiled it on my eclipse and it's java.lang.Comparable[] array;.
You can get the idea behind it here - What is a reifiable type?.
2

Type casts are done at runtime that's why you get a cast exception. Generics on the other hand are compile time features of Java. When you declare

class Foo<T> {
    T bar;
}

the field bar is actually of type Object (or if you use bounds like ? extends ... of whatever base class you chose). When you use the class for example like this

Foo<Foobar> foo = new Foo<>();
foo.bar = new Foobar();
Foobar foobar = foo.bar;

the compiler will translate the last assignment to something equivalent to

Foobar foobar = (Foobar) foo.bar;

because it knows that the return value, even though internally of type Object will always a Foobar.

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.