I am new to Java. As I known, It's basically the way that generics are implemented in Java via compiler trickery.
public Object doSomething(Object obj) {....}
public <T> T doSomething(T t) {....}
According to type erasion, the above two method is the same at runtime. The only different is the way we use this method, compiler will auto add type casting when we use generic method.
Foo newFoo = (Foo) my.doSomething(foo);
Similarly, when we use generic array in method, as the below shown:
public void <T> T[] f(T[] args){
return args;
}
public void <T> Object[] f(Object[] args){
return args;
}
I think the above two methods are same at runtime because of type erasion.
Integer[] a = {1, 2};
Integer[] b = test.f(a);
When I use this method, I think the generic method will throw an CaseException.
When we pass a
to test.f(a)
, the JVM cast Integer[]
to Object[]
.
And when we get the result from this method, the JVM will also cast Object[]
to Integer[]
and this cast will throw an CaseException. because array in java is support covariant but not contravariant.
As a result, the above code works in both compile and runtime. There must be something wrong about my understanding. But I can not find out. Can anyone help me? Thank you!