A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Programmer Certification (SCJP/OCPJP)
WildCards in Generics
Joined: Apr 23, 2006
May 22, 2006 11:58:00
Can someone explain the deal with wildcards in generics?
Pg.594 SCJP5 Sierra & Bates has an example with comment:
//adding is sometimes OK with super.
I'm somewhat confused with the word "sometimes"??
Also the deal with the ability to add (/NOT add) anything which has a ? wildcard type.
1.) <? extends ABCD>
2.) <? super ABCD>
Thanks guys in anticipation.
Joined: Apr 16, 2006
May 22, 2006 13:17:00
I *think* it's only legal to add to a generic collection with the wildcard if it's the return type.
public <T> List<? extends Number> someMethod(
I think this method can add to the List before it returns it.
But when you have say:
List list = new
<? extends Number>();
you can't add to this collection.
Don't have 1.5 here at work so my syntax may be wrong. Can someone confirm or deny if logic is correct?
Also, the K & B book did state the following:
1.) <? extends ABCD> -- can't modify
2.) <? super ABCD> -- can modify
3.) <?> -- can't modify
[ May 22, 2006: Message edited by: Shawn Kuenzler ]
Joined: Nov 14, 2005
May 22, 2006 23:55:00
<? extends ABCD>
List <? extends ABCD> can refer to any list of ABCD subclass
<? super ABCD>
List <? super ABCD> can refer to list of any super class of ABCD
List <?> can refer to List of any object.
"Know where to find the solution and how to use it - that's the secret of success."
subject: WildCards in Generics
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014