[ACCEPTED]-Explanation of the get-put principle-generics

Accepted answer
Score: 178

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

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

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

More Related questions