2

for code

import java.util.*;

interface Sample{

}

public class TypeTest implements Sample{
    public static void main(String[] args) {
        Set<Object> objs = new HashSet<>();
        objs.add(new TypeTest());
        List<? extends Sample> objList = (List<? extends Sample>) new ArrayList<>(objs);
        for (Sample t : objList) {
            System.out.println(t.toString());
        }
    }
}

it can run in eclipse and output TypeTest@7852e922 but javac will get an error:

incompatible types: ArrayList<Object> cannot be converted to List<? extends Sample>
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
andy
  • 1,336
  • 9
  • 23
  • Do you have 2 different JDKs installed on your system? – Blue May 16 '16 at 13:37
  • What version of javac? What Java level is your Eclipse project configured to use? – E-Riz May 16 '16 at 13:37
  • By the way, I don't think you even need the cast if you use a recent version of Java (7+); the compiler can imply the type parameters of the instantiation from the variable declaration. – E-Riz May 16 '16 at 13:39
  • Im able to reproduce this with jdk 1.8 and Eclipse 4.5 using the same jdk. The problem seems to be similar to...http://stackoverflow.com/q/2858799/1069114 and http://stackoverflow.com/q/3000177/1069114. – Pradhan May 16 '16 at 13:50
  • Yes eclipse allowing this, is wrong. Though honestly: diamond operator plus cast _is_ perverse. – Joop Eggen May 16 '16 at 14:11
  • @Blue no, only install JDK1.8.0_92 – andy May 16 '16 at 14:33
  • @E-Riz javac version is 1.8.0_92 and java level also configured as 1.8 in eclipse project – andy May 16 '16 at 14:34

1 Answers1

3

This code should not compile. The problem is that the inferred type of new ArrayList<>(objs) is ArrayList<Object> because you have passed the constructor a Set<Object> as the parameter. But ArrayList<Object> is not a subtype of List<? extends Sample>.

Change

    Set<Object> objs = new HashSet<>();

to

    Set<? extends Sample> objs = new HashSet<>();

and the code should compile ... provided that TypeTest is a subtype of Sample.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216