• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use Generic on Map

 
Joseph Si
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic