Reputation: 1650
Below are the two methods, one of which casts Object to Generic type and the other one casts Object[] to Generic type array.
public static <T> T returnElement(T a){
Object obj = new Object();
return (T)obj;
}
public static <T> T[] returnArray(T[] a){
Object obj[] = new Object[10];
return (T[])obj;
}
When I printed the result of the both methods, casts Object[] to Generic type[] succeeds and prints java.lang.Object. I am not able understand why the returnArray() does not throw ClassCastException and what is the difference between both casting?
System.out.println(ArrayAlg.<String>returnArray(new String[]{"a","b","c"})); // prints java.lang.Object
System.out.println(ArrayAlg.<String>returnElement("s")); //ClassCastException
Upvotes: 2
Views: 212
Reputation: 9100
This is because of the overloads for the println
method. For arrays, it has no special overload, the println(Object)
will be called, so no casting there. For the single element the println(String)
overload was selected at compile time and that casting is done after the return of the Object value.
Besides the arrays are covariant in Java (though they should be invariant in case generics were introduced earlier). In case the methods the casts are to Object[]
and Object
because of type erasure, so there are no ClassCastException
s.
Upvotes: 2