tags:

views:

81

answers:

2

I have read O'Reilly book, in that i came to know this GET and PUT rule

Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you both get and put.

exception is:

*)You cannot put anything into a type declared with an EXTENDS wildcard except for the value null, which belongs to every reference type

*)you cannot get anything out from a type declared with an SUPER wildcard except for a value of type Object, which is a super type of every reference type

can any one help me to explore this rule,at depth.If possible,please put them hierarchy manner

+8  A: 

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.)

Jon Skeet
but while fetching a fruit from Collection<?extends Fruits>,you may get any fruit not the banana.similarly,while putting a fruit to it,u may add any thing which may not belong to banana fruits
JavaResp
Java will prevent you from adding anything other than null to a `Collection<? extends Fruit>` for exactly that reason, and you'd have to explicitly cast the result of fetching an item, for precisely those reasons.
Jon Skeet
thanks for referring such a nice book
JavaResp
+2  A: 

Dont know if you already saw this, but the following has a pretty good explanation...

http://codeidol.com/java/javagenerics/Subtyping-and-Wildcards/The-Get-and-Put-Principle/

OpenSource