This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Use Generic on Map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use Generic on Map" Watch "Use Generic on Map" New topic
Author

Use Generic on Map

Joseph Si
Greenhorn

Joined: Dec 15, 2006
Posts: 1
I like to implement a map to store a bunch of different objects, with the key of the map to be the Class of the object, and the value to be the object itself. So when I attempt to retrieve the cached object, I will pass in the Class type, and the stored instance will be return.

Without using Generic:
Map map = new HashMap();
map.put(String.class, "example");
String example = (String)map.get(String.class);

I hope to remove the casting when I retrieve the copy by using Generic.
For example:
Map <Class<?>, ?> map = new HashMap();
map.put(String.class, "example"); <--- Error complains I cannot put a String in place of Object

I guess my first question would be if it is possible and if so, can someone show me what I am doing wrong?

Thanks
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi Joseph,


seems to be your first posting, so

Welcome to the ranch!


But sorry, I think what you want to do cannot be done at all.
Your assignment is correct, but the <?> stands for an unknown type.
The compiler can make the proper castings for you only when the type is known. Otherwise it's just Object.
You also cannot add anything (except null) to a Map or Collection with the type <?> or <? extends SomeClass>.
Only to ones with <? super AnyClass>.

But at least, the weekend is near!


Yours,
Bu.


all events occur in real time
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Use Generic on Map
 
Similar Threads
converting Array Of Objects to Array Of Strings
Do I have to override equals() due to using an object as a hashmap key? Yes..but..
Struggling with generics, "unchecked call to put()"
How to Set HashMap in request attribute using JSTL Tag
Query on enhanced FOR loop