GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Using Generics, HashMap with two different objects as Keys Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using Generics, HashMap with two different objects as Keys" Watch "Using Generics, HashMap with two different objects as Keys" New topic
Author

Using Generics, HashMap with two different objects as Keys

arunkumar subramanian
Ranch Hand

Joined: Jun 10, 2008
Posts: 32
How to achieve something like this using Generics

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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>();


[Jess in Action][AskingGoodQuestions]
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

You can do this:



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.
arunkumar subramanian
Ranch Hand

Joined: Jun 10, 2008
Posts: 32
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
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.
 
GeeCON Prague 2014
 
subject: Using Generics, HashMap with two different objects as Keys