I am sure you would not like the approach of retrieving all the keys and then iterating through them to find out if it's value is what you want. If your hashtable is expected to be large, there might be something wrong in the way you are addressing the problem. It might help if you can give a better idea of why you want to do this. Another option might be to maintain a second hashtable which uses the values as the keys and the keys as the values just for this particular lookup. Again, it depends on what you are trying to do.
posted 13 years ago
What if you use a JavaBean as a value for the Hashtable? In JavaBean you would have two properties a key and a value. When key of hashtable is set, key ptoperty is also set. Samething with value of particular record of the Collection. Then when you retrieve the value from Collection you actually get Collection of values then get the bean you want and get the key: HashBean.getKey()?
If you require two-way hash-based lookup, then create your own object that aggregates two HashMaps (not Hashtable, by the way--don't use that class over a HashMap unless you have a really good reason).
Instead of this approach, you could also have this class implement the Map interface and simply pass all the Map methods thru to your internal map instance (and populate the reverseMap when necessary). Then just add that one extra getByValue() method to use the reverseMap.
Or, instead of adding that one extra method directly to your TwoWayHashMap API, you could add a method instead that returns an instance of the Map interface backed by the reverseMap. That way you could get all of the Map functionality of the map when looking up forwards or backwards.
If you take this last approach, I highly recommend you return an unmodifiable view of the reverseMap. This forces the caller to modify your TwoWayHashMap through the main API only, not through an obtained reverseMap.
Using this method, it's important to note that this TwoWayHashMap is not thread-safe. That is, if one thread is putting in the main map, and another thread is reading from the view of the reverseMap, it's possible to get weird and inconsistent results. Initializing your internal maps to be synchronized won't help either because you need to sync operations *between* the two internal maps.
Fortunately, the good people at Sun already thought of this. All you have to do is have clients of this object instantiate sync'd TwoWayHashMaps wherever they are needed, using the standard mechanism:
posted 13 years ago
Oh, and I forgot to add....if a caller wants to lookup a key on this new TwoWayHashMap by value, no problem: