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?
Joined: Aug 25, 2006
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>.