aspose file tools*
The moose likes Java in General and the fly likes Generics confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics confusion" Watch "Generics confusion" New topic
Author

Generics confusion

Kousik Majumder
Ranch Hand

Joined: Sep 30, 2007
Posts: 229
Hi all,

Can somebody tell me when should I use wildchar character or write Object instead of that in method signature or other places?

e.g
or


Thanks in Advance,
Kousik
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

For instance:



"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Kousik Majumder
Ranch Hand

Joined: Sep 30, 2007
Posts: 229
So the point is that if there is a dependency on other class then we should use wildchar character otherwise not. Is that so?
Can't we use this to make methods generic ?


Kousik Majumder
Ranch Hand

Joined: Sep 30, 2007
Posts: 229
So the point is that if there is a dependency on other class then we should use wildchar character otherwise not. Is that so?
Can't we use this to make methods generic ?

Suppose in an interface what should be the ideal way to declare a generic method?


Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

The rules about ?:

- ? super T: the compiler doesn't know a lot about the actual type, only that all instances of T match. Therefore you can add elements that are instances of T or a sub type. When you want to retrieve the compiler knows nothing so Object is the only possibility without casting

- ? extends T: this is just the other way around. The actual type is unknown so adding is not allowed. If T is Serializable, the actual type could be String, Integer, anything. Adding just any Serializable object is therefore not allowed. When you want to retrieve the compiler knows that no matter the type, everything IS-A T, so you can assign the elements to a reference of T without casting.

? is simply the same as "? extends Object".


Now these rules should allow you to choose what you want to return.
- Do you need to put anything in the outer map? Then "?" is not good for the key. The "?"s in the value are still allowed, because any Map is a Map<?,?>. If you don't need to put anything in the outer map then "?" is just fine.

- Do you need to put anything in the inner maps? Then "?" is not good for either the key or the value. If you don't need to put anything in the inner maps then "?" is just fine.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
Don't get me started about those stupid light bulbs.
 
subject: Generics confusion