I am learning Java 7 generics, reading Cay Horstmann, Core Java7, Volume I, on page 716. I dont understand why the run time error (cast illegal) occurs, please see code below. Can anyone explain it to me better than Cay does?
public class ProcessArgs
{
public static <T extends Comparable> T[] minmax(T... a)
{
Object[] mm = new Object[2];
mm[0] = a[0];
mm[1] = a[1];
if (mm[0] instanceof Comparable)
{
System.out.println("Comparable"); // this is True, prints Comparable at run-time
}
return (T[]) mm; // run-time error here
/* Run-Time ERROR as below:
ComparableException in thread "main"
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at ProcessArgs.minmax(ProcessArgs.java:13)
at ProcessArgs.main(ProcessArgs.java:18)
*/
}
public static void main(String[] args)
{
String[] sa = minmax("Hello","World"); // ERROR, illegal cast
System.out.println(sa[0] + sa[1]);
Object o = "Hello World"; //works - if we comment out the method call to minmax above
Comparable<String> s = (Comparable) o; // works
Comparable s2 = (Comparable) o; // works
System.out.println(s + " " + (String) s2); // works
return;
}
}
It throws an error because the actual type you created, Object[]
is NOT a Comparable
. Java generics deal pretty poorly with arrays, you should try to use Collections if possible. For this case, you can create an array of the proper type using reflection:
T[] mm = (T[]) Array.newInstance(a[0].getClass(), 2 );
Given these two lines:
Object o = "Hello World"; //works - if we comment out the method call to minmax above
Comparable<String> s = (Comparable) o; // works
The second line works because the string "Hello World"
actually is a Comparable
.
But Object[]
isn't, its type is Object[]
, so it can't be cast.
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