Map的keySet()方法得到的顺序问题


一. 结论

  • Map的常用实现类Hashtable、TreeMap、HashMap、LinkedHashMap的keySet()方法获取key的顺序:
    • LinkedHashMap.keySet()得到的Set是有序的;
    • 其他三个得到的Set都是无序的。

二. 代码实现

public class MapKeySetTest {

    private Hashtable<String, String> hashtable = new Hashtable<>();
    private TreeMap<String, String> treeMap = new TreeMap<>();
    private HashMap<String, String> hashMap = new HashMap<>();
    private LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();

    public void initData(){
        for(int i=0; i<31; i++){
            hashtable.put(String.valueOf(i),i+"");
            treeMap.put(String.valueOf(i),i+"");
            hashMap.put(String.valueOf(i),i+"");
            linkedHashMap.put(String.valueOf(i),i+"");
        }
    }

    public static void main(String[] args) {
        MapKeySetTest test = new MapKeySetTest();
        test.initData();

        System.out.println("HashTable:"+test.hashtable.keySet());
        System.out.println("TreeMap:"+test.treeMap.keySet());
        System.out.println("HashMap:"+test.hashMap.keySet());
        System.out.println("LinkedHashMap:"+test.linkedHashMap.keySet());
    }

}
  • 结果如下:
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]
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值