Java HashMapについては追加順に並べ替えが表示されていません

1920 ワード

一般的にHashMapのアクセス順序は一致しません.たとえば、次のようになります.
@Test
2
public void test(){
3
    HashMapmap=new HashMap();
4
    map.put("1", "111");
5
    map.put("2", "122");
6
    map.put("3", "133");
7
    map.put("4", "144");
8
    map.put("5", "155");
9
    for(String str:map.keySet()){
10
        System.out.println("key is "+str+" value is "+map.get(str));
11
    }
12
}

 出力の結果、key is 3 value is 133 key is 2 value is 122 key is 1 value is 111 key is 5 value is 155 key is 4 value is 144、つまりデータの取り出し順序が格納時と同じであることは保証されないが、LinkedHashMapはこれを行うことができる
LinkedHashMaplinkedHashMap=new LinkedHashMap();
2
linkedHashMap.put("1", "111");
3
linkedHashMap.put("2", "222");
4
linkedHashMap.put("3", "333");
5
linkedHashMap.put("4", "444");
6
linkedHashMap.put("5", "555");
7
for(String str:linkedHashMap.keySet()){
8
    System.out.println("key is "+str+" value is "+linkedHashMap.get(str));
9
}

出力結果:key is 1 value is 111 key is 2 value is 222 key is 3 value is 333 key is 4 value is 444 key is 5 value is 555
TreeMapもできます 
TreeMapmap=new TreeMap();
2
map.put("1", "1111");
3
map.put("2", "2222");
4
map.put("3", "3333");
5
map.put("4", "4444");
6
map.put("5", "5555");
7
for(String str:map.keySet()){
8
    System.out.println("key is "+str+" value is "+map.get(str));
9
}

出力結果key is 1 value is 1111 key is 2 value is 2222 key is 3 value is 3333 key is 4 value is 4444 key is 5 value is 5555