It's not a secret anymore!
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use Generic on Map" Watch "Use Generic on Map" New topic

Use Generic on Map

Joseph Si

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?

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!


all events occur in real time
I agree. Here's the link:
subject: Use Generic on Map
It's not a secret anymore!