赞
踩
探究Hashtable、TreeMap、HashMap、LinkedHashMap四个Map的keySet()顺序问题。
- package com.jxp;
-
- import java.util.HashMap;
- import java.util.Hashtable;
- import java.util.LinkedHashMap;
- import java.util.TreeMap;
-
- import org.junit.Before;
- import org.junit.Test;
-
- public class MapTest {
-
- private Hashtable<String , String> hashTable;
- private TreeMap<String , String> treeMap;
- private HashMap<String , String> hashMap;
- private LinkedHashMap<String, String> linkedHashMap;
-
- @Before
- public void init() {
- hashTable = new Hashtable<String , String>();
- treeMap = new TreeMap<String , String>();
- hashMap = new HashMap<String , String>();
- linkedHashMap = new LinkedHashMap<String , String>();
-
- for(int i = 0; i < 31; i++) {
- hashTable.put(String.valueOf(i), i + "" + i);
- treeMap.put(String.valueOf(i), i + "" + i);
- hashMap.put(String.valueOf(i), i + "" + i);
- linkedHashMap.put(String.valueOf(i), i + "" + i);
- }
- }
-
- @Test
- public void indexTest() {
- System.out.println("Hashtable: " + hashTable.keySet());
- System.out.println("TreeMap: " + treeMap.keySet());
- System.out.println("HashMap: " + hashMap.keySet());
- System.out.println("LinkedHashMap: " + linkedHashMap.keySet());
- }
- }
运行indexTest方法,结果如下
- Hashtable: [30, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 29, 8, 28, 7, 27, 6, 26, 5, 25, 4, 24, 3, 23, 2, 22, 1, 21, 0, 20]
- TreeMap: [0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 4, 5, 6, 7, 8, 9]
- HashMap: [22, 23, 24, 25, 26, 27, 28, 29, 30, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21]
- LinkedHashMap: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
上述打印的时候,尽量从keySet()得到Iterator进行取值。可以看出LinkedHashMap.keySet()拿到的Set是按照顺序的,其余三个都是乱序。因此,当遇到对数据排序有严格要求的问题时,要用LinkedHashMap。
深层原因,后期自行查看源码。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。