代码可以 运行 在 eclipse 中,但不能在 javac 中

a code can run in eclipse, but not javac

代码

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());
        }
    }
}

在eclipse中可以运行输出TypeTest@7852e922但是javac会报错:

incompatible types: ArrayList<Object> cannot be converted to List<? extends Sample>

此代码不应编译。问题是 new ArrayList<>(objs) 的推断类型是 ArrayList<Object> 因为您已经将构造函数 a Set<Object> 作为参数传递。但是 ArrayList<Object> 不是 List<? extends Sample> 的子类型。

改变

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

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

并且代码应该可以编译...前提是 TypeTest 是 Sample.

的子类型