Generics compilation failure casting List<? extends Set...> to List<Set...> under Java 7

Andrew Phillips andrew at jclouds.org
Sat Dec 31 07:17:21 PST 2011


Hi all

During some recent work to get jclouds to compile under Java 7 I came  
across a generics compilation failure that can be reproduced using the  
following sample code:

classGenericCompilationFailureDemo{
     List<?extendsGenericCompilationFailureDemo>newList(){
         returnnewArrayList<GenericCompilationFailureDemo>();
     };

     voiduseList(){
         List<GenericCompilationFailureDemo>list =
             (List<GenericCompilationFailureDemo>)newList();
     }

     List<?extendsSet<GenericCompilationFailureDemo>>newListOfSpecificSets(){
         returnnewArrayList<Set<GenericCompilationFailureDemo>>();
     };

     voiduseListOfSpecificSets(){
         List<Set<GenericCompilationFailureDemo>>listOfSpecificSets =
             (List<Set<GenericCompilationFailureDemo>>)newListOfSpecificSets();
     }

     List<?extendsSet<?extendsGenericCompilationFailureDemo>>newListOfSets(){
         returnnewArrayList<Set<?extendsGenericCompilationFailureDemo>>();
     };

     voiduseListOfSet(){
         List<Set<?extendsGenericCompilationFailureDemo>>listOfSets =
             (List<Set<?extendsGenericCompilationFailureDemo>>)newListOfSets();
     }
}


This passes under Sun JDK 1.6.0_20 and _24 but fails under Oracle JDK  
1.7.0 and _01 with:

[ERROR]src\main\java\GenericCompilationFailureDemo.java:[56,78]error:inconvertible  
types

The comments and tentative answer to my resulting StackOverflow question

http://stackoverflow.com/questions/8637937/why-does-a-generic-cast-of-a-list-extends-set-to-listset-succeed-on-sun

seem to suggest that this is a compiler bug. We found a simple  
workaround, by the way: do the cast in a separate method (see  
https://github.com/jclouds/jclouds/commit/1ba75f623f03908d87c2fddce46e276098f3db40).

Any comments or suggestion much appreciated! And a belated Merry  
Christmas and Happy New Year, of course ;-)

Regards


Andrew



More information about the compiler-dev mailing list