Created
June 1, 2012 08:10
-
-
Save keating/2850183 to your computer and use it in GitHub Desktop.
bidirectional hashMap for java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* bidirectional hashMap | |
* 双向的HashMap对应关系 | |
* | |
* @author keating_andy_given | |
*/ | |
public class BiHashMap<K,V> { | |
private Map<K, V> map = new HashMap<K, V>(); | |
private Map<V, K> reverse = new HashMap<V, K>(); | |
private BiHashMap(K[] keys, V[] values) { | |
for(int i=0; i < keys.length; i++) { | |
map.put(keys[i], values[i]); | |
reverse.put(values[i], keys[i]); | |
} | |
} | |
public V value(K k) { | |
return map.get(k); | |
} | |
public K key(V v) { | |
return reverse.get(v); | |
} | |
/** | |
* 必须满足基本的构造条件,否则返回null | |
* //todo 还需判断keys,values中是否有重复 | |
*/ | |
public static <K, V> BiHashMap<K, V> createBiHashMap(K[] keys, V[] values) { | |
if(keys == null || values == null) | |
return null; | |
if(keys.length != values.length) | |
return null; | |
return new BiHashMap<K, V>(keys, values); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment