我写了下面的代码
class Student {}
class Student1 extends Student {}
class Student2 extends Student {}
List<? extends Student> emp = new ArrayList<>();
emp.add(new Student()); // I do not want this to happen. at compile time it should give me error
emp.add(new Student1()); // this should happen
emp.add(new Student2()); // this should happen
但是在上面的代码中它不起作用,在所有 3 个添加中抛出编译错误。
有什么指点吗?
最佳答案
不,Java 中没有这样的选项可以将类型参数限制为给定类型的子类型。看起来您已经理解了语法 ? extends Type
的含义有点太字面意思了。 Type
通配符有上限,并且该范围始终包含在内。
如果您的想法确实有效,那么就不会有任何类型可以用来引用列表中的一般项目:最窄的此类类型是 Student
.
关于Java 集合泛型 <?扩展 Employee> 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868802/