Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics from Cay Horstmann, Core Java 7, Volume I, page 716

Tags:

java

generics

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;
  }
}
like image 868
Acid Rider Avatar asked May 22 '15 04:05

Acid Rider


1 Answers

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.

like image 62
markspace Avatar answered Sep 22 '22 14:09

markspace