Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object array to generic array

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?

like image 368
Johnny Willer Avatar asked Sep 04 '26 15:09

Johnny Willer


2 Answers

but why with generics works?

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

Object[] array = new Object[size];
like image 156
Bhesh Gurung Avatar answered Sep 07 '26 03:09

Bhesh Gurung


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.

like image 33
tiorthan Avatar answered Sep 07 '26 04:09

tiorthan