First, understand that the whole point of generics is to prevent this kind of thing; you want to know what kind of objects are in the map, so you don't have to do any explicit casting when you take them out.
But otherwise, you can accomplish it by using the nearest common ancestor of the various types as the type parameter (Object, in this case.)
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
but this basically defeats the whole purpose of Generics. And with or without generics, using different object types as keys in a Map, and storing different Object types as values in a Map would be typically considered a less than ideal solution. There are exceptions; but they are rare. So doing something like this should only be done with a lot of forethought and planning... and a lot of documentation & commenting about what is being done, and why.
What is it that you are trying to (ultimately) accomplish? There may be a better solution for you situation.
Joined: Jun 10, 2008
Thanks for your replies.
I'm trying to port the code from 1.4 to 1.5. Here is what I'm doing
-- Sample Code
author and iconoclast
Ugh. That's terrible, terrible code. Notice how it checks if result is null, and then if it is, it calls result.put()! The whole idea of storing an "Error" key in the result map if the result is empty is just bizarre; the fact that it's empty is going to be obvious, but by storing that key, you now make it necessary to check whether the single key is the Error key or just a single result! Ugh. Yuk, yuk, yuk.
Is it possible to redesign the whole thing? Just make getResultMap() return a map no matter what -- empty, if need be -- and then let "get()" simply return it. Whatever is checking for the "Error" key can just check for "isEmpty()" instead.
Otherwise, you have to make getResultMap() return HashMap<Object, Object> too.