关于HashMap的读取顺序

一般来说HashMap的存取顺序是不一致的,比如说:

@Test
public void test2(){
    HashMap<String, String>map=new HashMap<String, String>();
    map.put("1", "111");
    map.put("2", "122");
    map.put("3", "133");
    map.put("4", "144");
    map.put("5", "155");
    for(String str:map.keySet()){
        System.out.println("key is "+str+" value is "+map.get(str));
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 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可以做到这点

LinkedHashMap<String, String>linkedHashMap=new LinkedHashMap<String, String>();
linkedHashMap.put("1", "111");
linkedHashMap.put("2", "222");
linkedHashMap.put("3", "333");
linkedHashMap.put("4", "444");
linkedHashMap.put("5", "555");
for(String str:linkedHashMap.keySet()){
    System.out.println("key is "+str+" value is "+linkedHashMap.get(str));
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 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也可以做到

    TreeMap<String, String>map=new TreeMap<String, String>();
    map.put("1", "1111");
    map.put("2", "2222");
    map.put("3", "3333");
    map.put("4", "4444");
    map.put("5", "5555");
    for(String str:map.keySet()){
        System.out.println("key is "+str+" value is "+map.get(str));
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 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

转自:http://blog.csdn.net/cavvv/article/details/46754279

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值