获得-放入原则的解释

我读过奥莱利的书,因为我了解了这本 获取放置原则

  • 当结构中只有 走开值时,请使用 extends通配符。
  • 在结构中只有 放下值时使用 super通配符。
  • 当您都想从/放入结构时,不要使用通配符。

例外是:

  • 除了属于每个引用类型的值 null之外,不能将任何内容放入使用 extends通配符声明的类型中。

  • 除了 Object类型的值(它是每个引用类型的超类型)之外,您不能从使用 super通配符声明的类型中获取任何内容。

有没有人能帮助我深入探讨这个规则? 如果可能的话,请把他们的等级方式。

31959 次浏览

Consider a bunch of bananas. This is a Collection<? extends Fruit> in that it's a collection of a particular kind of fruit - but you don't know (from that declaration) what kind of fruit it's a collection of. You can get an item from it and know it will definitely be a fruit, but you can't add to it - you might be trying to add an apple to a bunch of bananas, which would definitely be wrong. You can add null to it, as that will be a valid value for any kind of fruit.

Now consider a fruitbowl. This is a Collection<? super Banana>, in that it's a collection of some type "greater than" Banana (for instance, Collection<Fruit> or Collection<TropicalFruit>). You can definitely add a banana to this, but if you fetch an item from the bowl you don't know what you'll get - it may well not be a banana. All you know for sure is that it will be a valid (possibly null) Object reference.

(In general, for Java generics questions, the Java Generics FAQ is an excellent resource which contains the answer to almost anything generics-related you're likely to throw at it.)