一個Map的工具類
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 這是一個用1.5寫的Map的工具類
*
* @author huanglq
*
* @param <K>
* @param <V>
*/
public class MapUtil<K, V> {
/**
* 這個方法只用於存放一個K-V的Map
*
* @param map
* @return
*/
@SuppressWarnings(value = { "unchecked" })
public K getMapKey(Map<K, V> map) {
Set set = map.keySet();
Iterator iterator = set.iterator();
if (iterator.hasNext()) {
return (K) iterator.next();
}
return null;
}
/**
* 獲得Map中特定value的key值
*
* @param map
* @param value
* @return
*/
@SuppressWarnings(value = { "unchecked" })
public K getMapKeyFromValue(Map<K, V> map, V value) {
Set set = map.keySet();
K key = null;
Iterator it = set.iterator();
while (it.hasNext()) {
key = (K) it.next();
if (value.equals(map.get(key))) {
return key;
}
}
throw new NullPointerException("沒有對應的Key值");
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
//這個Map要怎麼樣建都可以
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(null, "three");
//map.put(4, null);
//map的value不能為空,不然就沒意義,而且在用它時會出現java.lang.NullPointerException
System.out.println(map.get(null));
/*
* 輸出 three
*/
MapUtil<Integer, String> mapUtil = new MapUtil<Integer, String>();
// Integer a=(Integer)mapUtil.getMapKey(map);
// System.out.println(a);
Integer key = (Integer) mapUtil.getMapKeyFromValue(map, "two");
System.out.println(key);
/*
* 輸出 2
*/
Integer key3 = (Integer) mapUtil.getMapKeyFromValue(map, "three");
System.out.println(key3);
/*
* 輸出 null
*/
Integer key2 = (Integer) mapUtil.getMapKeyFromValue(map, "twoo");
System.out.println(key2);
/*
* Exception in thread "main" java.lang.NullPointerException: 沒有對應的Key值
*/
}
}
[/code]