理解 Java 中的通用上界通配符

huangapple go评论70阅读模式
英文:

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&lt;? extends Object&gt; list) {
list.add(&quot;quack&quot;); //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&lt;? super String&gt; list) {
    list.add(&quot;quack&quot;); //does compile
   }

huangapple
  • 本文由 发表于 2020年10月9日 15:50:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64276019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定