An array of objects to a common array

See code

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

      

it obviously doesn't work, I understand perfectly.

but why does it work with generics?

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

      

if T is an integer class, after this line the array will be of type Object [], but why use it? doesn't throw ClassCastException?

+3


source to share


2 answers


but why does it work with generics?

This is because the generic version is erased and compiled like this:



Object[] array = new Object[size];

      

+3


source


The execution type is executed at runtime, so you get a cast exception. On the other hand, generics are Java compile time functions. When you declare

class Foo<T> {
    T bar;
}

      

the fields pane is actually of type Object (or if you use borders like? extends ... whatever base class you choose). When you use a class like

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

      



the compiler will translate the last assignment to something equivalent

Foobar foobar = (Foobar) foo.bar;

      

because it knows the return value even though inside the type object will always be Foobar.

+2


source







All Articles