工做中對於列表的輸出最經常使用到是List,但也有ArrayList處理不了的狀況,好比要根據日期對列表進行分類的狀況,相似這樣的界面:
2011-3-7
標題1
標題2
標題3
2011-3-6
標題1
標題2
2011-3-5
標題1
標題2
標題3
標題4
這個時候難免要用到Map,HashMap和LinkedHashMap都是實現Map接口,區別在於HashMap並非按插入次序順序存放的,而LinkedHashMap是順序存放的,看下面的例子:
public
static
void main(String[] args) {
Map<String,String> hashmap =
new HashMap<String,String>();
Map<String,String> linkmap =
new LinkedHashMap<String,String>();
for(
int i=0;i<10;i++){
hashmap.put(
""+i, ""+i);
linkmap.put(
""+i, ""+i);
}
System.out.println(
"HashMap遍歷輸出:");
for(Entry<String,String> entry:hashmap.entrySet()){
System.out.print(entry.getKey()+
" ");
}
System.out.println("");
System.out.println(
"LinkedHashMap遍歷輸出:");
for(Entry<String,String> entry:linkmap.entrySet()){
System.out.print(entry.getKey()+
" ");
}
}
輸出結果
HashMap遍歷輸出: 3 2 1 0 7 6 5 4 9 8 LinkedHashMap遍歷輸出: 0 1 2 3 4 5 6 7 8 9
在平常的開發中,用到HashMap的狀況很是多,LinkedHashMap較爲少用,由於咱們不多對MAP的順序有要求。這裏作個備註,當對順序有要求的狀況,咱們就要用到LinkedHashMap