[TYPES] Java generics unsoundness?

Eijiro Sumii eijiro.sumii at gmail.com
Sat Sep 30 21:18:45 EDT 2006

Dear all,

Hiromasa Kido, an undergraduate student in the University of Tokyo,
has found the problem below in the implementation of generics in Java.
 Another student, Kouta Mizushima, in Tsukuba University, reported
that it also reproduces in Eclipse (which has its own compiler).

C:\WINDOWS\Temp>c:\progra~1\java\jdk1.6.0\bin\java -version
java version "1.6.0-rc"
Java(TM) SE Runtime Environment (build 1.6.0-rc-b100)
Java HotSpot(TM) Client VM (build 1.6.0-rc-b100, mixed mode, sharing)

C:\WINDOWS\Temp>type B.java
class A{
       public int compareTo(Object o){
               return 0;

class B extends A implements Comparable<B>{
       public int compareTo(B b){
               return 0;

       public static void main(String[] argv){
               System.out.println(new B().compareTo(new Object()));

C:\WINDOWS\Temp>c:\progra~1\java\jdk1.6.0\bin\javac -Xlint B.java

C:\WINDOWS\Temp>c:\progra~1\java\jdk1.6.0\bin\java B
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot
 be cast to B
        at B.compareTo(B.java:7)
        at B.main(B.java:13)


Here is my understanding (confirmed by Atsushi Igarashi) of the
problem: after erasure (i.e., replacing every type variable with the
Object class), an auxiliary method (called bridged method) like

  public int compareTo(Object x){
    return compareTo((B)x);

is created by the compiler in class B.  However, this additional
method happens to override A.compareTo and raises an unexpected

We have already submitted a bug report to Sun.  My question is: Is
this a bug in the compiler, or in the design of the language?  On one
hand, it is a compiler bug because the bridge method, inserted by the
compiler, is doing the harm.  On the other hand, it would be hard for
any compilers to implement generic interfaces without bridge methods
(unless we modify the present JVM).  In my understading, such
overriding as above is not forbidden in the current language
specification (page 227 and page 478 perhaps).

Does any expert in this list have a word on this matter...?

Thanks in advance,

Eijiro Sumii

More information about the Types-list mailing list