Search code examples
javaeclipselistcollectionstype-safety

a code can run in eclipse, but not javac


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>

Solution

  • 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.