当前位置:   article > 正文

keySet()顺序_keyset排序

keyset排序

探究Hashtable、TreeMap、HashMap、LinkedHashMap四个Map的keySet()顺序问题。

  1. package com.jxp;
  2. import java.util.HashMap;
  3. import java.util.Hashtable;
  4. import java.util.LinkedHashMap;
  5. import java.util.TreeMap;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. public class MapTest {
  9. private Hashtable<String , String> hashTable;
  10. private TreeMap<String , String> treeMap;
  11. private HashMap<String , String> hashMap;
  12. private LinkedHashMap<String, String> linkedHashMap;
  13. @Before
  14. public void init() {
  15. hashTable = new Hashtable<String , String>();
  16. treeMap = new TreeMap<String , String>();
  17. hashMap = new HashMap<String , String>();
  18. linkedHashMap = new LinkedHashMap<String , String>();
  19. for(int i = 0; i < 31; i++) {
  20. hashTable.put(String.valueOf(i), i + "" + i);
  21. treeMap.put(String.valueOf(i), i + "" + i);
  22. hashMap.put(String.valueOf(i), i + "" + i);
  23. linkedHashMap.put(String.valueOf(i), i + "" + i);
  24. }
  25. }
  26. @Test
  27. public void indexTest() {
  28. System.out.println("Hashtable: " + hashTable.keySet());
  29. System.out.println("TreeMap: " + treeMap.keySet());
  30. System.out.println("HashMap: " + hashMap.keySet());
  31. System.out.println("LinkedHashMap: " + linkedHashMap.keySet());
  32. }
  33. }

运行indexTest方法,结果如下

  1. 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]
  2. 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]
  3. 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]
  4. 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。

深层原因,后期自行查看源码。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/306658
推荐阅读
相关标签
  

闽ICP备14008679号