英文:
Understanding generic upper bound wildcarts in java
问题
下面方法中的上界通配符表示我们可以传入一个包含类型为Object的元素或任何包含类型为Object子类的元素的List,我不明白以下代码为什么无法编译通过,因为String是Object的子类:
public static void addSound(List<? extends Object> list) {
list.add("quack"); //无法编译通过
}
英文:
The upper bound wildcard in the method below means we can pass in a list that contains elements of type Object or any List containing elements of type which is subclass Object, I am not understanding why the following is not compiling, because string is subclass of Object:
public static void addSound(List<? extends Object> list) {
list.add("quack"); //does not compile
}
答案1
得分: 1
上界泛型是不可变的。扩展的类型可以是任何扩展自object的类型,它可以是一系列的Ducks。然后你会看到为什么它行不通。(list.add(new Duck())与“quack”不同)
但下界是有效的。
public static void addSound(List<? super String> list) {
list.add("quack"); //编译通过
}
英文:
Upper bounded generics are immutable. The extended type can be anything that extends object, it could be a list of Ducks. and then you see why it can't work. (list.add(new Duck()) is not the same as "quack")
Lower bound work though
public static void addSound(List<? super String> list) {
list.add("quack"); //does compile
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论