Generics compilation failure casting List<? extends Set...> to List<Set...> under Java 7
Rémi Forax
forax at univ-mlv.fr
Sat Dec 31 07:56:15 PST 2011
On 12/31/2011 04:17 PM, Andrew Phillips wrote:
> 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
I think it's a bug too, and javac is (was) known to be to strict when
checking assignment conversions.
Your program can be reduced to
List<Set<? extends String>> a = null;
List<? extends Set<? extends String>> b = a; // 1
List<? extends Set<? extends String>> c = null;
List<Set<? extends String>> d = (List<Set<? extends
String>>)c; // 2
(1) compiles but the reverse (2) doesn't compile.
You should check in the bug is already in the bug DB (bugs.sun.com) and
files a bug report if it's not already reported.
cheers,
Rémi
More information about the compiler-dev
mailing list