Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java Generics cast error - from Cay Horstmann Volume I, page 716 (Java 7 book)

Yuri BudilovMay 22 2015 — edited May 22 2015

Hello Java experts

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?

Thanks!

-------------------------------------

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;
}

}

This post has been answered by TPD-Opitz on May 22 2015
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 19 2015
Added on May 22 2015
2 comments
536 views