標籤:style color java 使用 os io for ar
執行個體如下:
public String getReportURL() throws Exception {
String reportURL = parameterMap.get("showPageUrl").toString() + "showPageNum=1";
Iterator it = parameterMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object keyObj = entry.getKey();
Object valObj = entry.getValue();
if (keyObj != null && keyObj.toString().length() > 0 && valObj != null && valObj.toString().length() > 0) {
String key = keyObj.toString();
String val = valObj.toString();
if (!"showPageNum".equals(key))
reportURL += "&" + URLEncoder.encode(key, "gb2312") + "=" + URLEncoder.encode(val, "gb2312");
}
}
return reportURL;
}
Map類提供了一個稱為entrySet()的方法,這個方法返回一個Map.Entry執行個體化後的對象集。 接著,Map.Entry類提供了一個getKey()方法和一個getValue()方法
同時,提供給開發人員一個同時保持了關鍵字和其對應的值的類。Map.Entry同時也提供了一個setValue()方法,程式員可以使用它修改map裡面的值。
map內部是按照hash演算法儲存的,但如果能對map排序在某些時候還是有用的
/**
* @param h
* @return
* 實現對map按照value升序排序
*/
@SuppressWarnings("unchecked")
public static Map.Entry[] getSortedHashtableByValue(Map h) {
Set set = h.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set .size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
return key1.compareTo(key2);
}
});
return entries;
}
/**
* @param h
* @return
* 實現對map按照key排序
*/
@SuppressWarnings("unchecked")
public static Map.Entry[] getSortedHashtableByKey(Map h) {
Set set = h.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Object key1 = ((Map.Entry) arg0).getKey();
Object key2 = ((Map.Entry) arg1).getKey();
return ((Comparable) key1).compareTo(key2);
}
});
return entries;
}
Map的keySet方法
2008-07-12 10:44
有一個Map對象,這時候使用keySet()方法擷取所有的key值,比如:
Map map = new HashMap();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
Set keys1 = map.keySet();
Set keys2 = map.keySet();
Set keys3 = map.keySet();
上面三個set對象key1,key2,key3引用的是一個對象。這是map的keySet()方法只返回一個set執行個體,所以當從key1中刪除一個對象時候,key2和key3將會受到影響。
keys1.remove(1);
System.out.println(keys1);
System.out.println(keys2);
System.out.println(keys3);
列印結果為:
[2, 4, 3]
[2, 4, 3]
[2, 4, 3]
在使用map時有時會出現此類的錯誤
java.util.ConcurrentModificationException
在執行如下 代碼時會出此錯誤:
Set<String> keySet=map.keySet();
for(String key:keySet){
map.remove(key);
}
原因是刪除一個Entry之後keySet集合不對,在執行迴圈時會出現錯誤。將代碼改為如下則能解決此問題:
String[] keySet=map.keySet().toArray(new String[0])
for(String key:keySet){
map.remove(key);
}
因為加了toArray所以新的集合和原來的keySet就沒有了關係,所以也就不會出錯了