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?
but why with generics works?
It's because the generic version is type-erased and compiled to following -
Object[] array = new Object[size];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With