Well I needed this and I didin't want to take a whole different lib just to use one class.
So I made this one, it's quite basic and simple.
Since I'm not so good in java, I need to know how this should be done correctly - all feedback is welcome.
Code:
import java.util.HashMap;
import java.util.Map;
/**
* BidirectionalMap - The bidirectional hash-map.
*
* @author wOok
*/
public class BidiMap<K, V> {
/**
* The regular type hash-map.
*/
private Map<K, V> map = new HashMap<K, V>();
/**
* The inverted type hash-map.
*/
private Map<V, K> invertedMap = new HashMap<V, K>();
/**
* Puts data into bidirectional map.
*
* @param key
* the key
* @param value
* the value
*/
public void put(K key, V value) {
map.put(key, value);
invertedMap.put(value, key);
}
/**
* Gets data from the bidirectional map.
*
* @param key
* the key
*
* @return the value
*/
public Object get(Object key) {
Object entry = map.get(key);
if (entry == null) {
entry = invertedMap.get(key);
}
return entry;
}
/**
* Removes the key from bidirectional map.
*
* @param key
* the key
*/
public void remove(Object key) {
boolean first = false;
Object entry = map.get(key);
if (entry == null) {
first = true;
entry = invertedMap.get(key);
}
if (first) {
map.remove(entry);
invertedMap.remove(key);
} else {
invertedMap.remove(entry);
map.remove(key);
}
}
/**
* Gets the bidirectional map size.
*
* @return the bidirectional map size
*/
public int size() {
return map.size();
}
}
Example how it works:
Code:
BidiMap<Integer, Integer> map = new BidiMap<Integer, Integer>();
map.put(10, 50);
map.get(10); // this will return 50
map.get(50); // this will return 10
Well it can be used in many cases, as Graham mentioned before a good example is to convert normal item id to noted one, and from note back to item.