`
samuschen
  • 浏览: 399007 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

LinkedHashMap和HashMap的比较使用

 
阅读更多

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class TestLinkedHashMap {

  public static void main(String args[])
  {
   System.out.println("*************************LinkedHashMap*************");
   Map<Integer,String> map = new LinkedHashMap<Integer,String>();
   map.put(6, "apple");
   map.put(3, "banana");
   map.put(2,"pear");
  
   for (Iterator it =  map.keySet().iterator();it.hasNext();)
   {
    Object key = it.next();
    System.out.println( key+"="+ map.get(key));
   }
  
   System.out.println("*************************HashMap*************");
   Map<Integer,String> map1 = new  HashMap<Integer,String>();
   map1.put(6, "apple");
   map1.put(3, "banana");
   map1.put(2,"pear");
  
   for (Iterator it =  map1.keySet().iterator();it.hasNext();)
   {
    Object key = it.next();
    System.out.println( key+"="+ map1.get(key));
   }
  }
}

运行结果如下:

*************************LinkedHashMap*************
6=apple
3=banana
2=pear
*************************HashMap**************************
2=pear
6=apple
3=banana

分析:LinkedHashmap 的特点是put进去的对象位置未发生变化,而HashMap会发生变化.

LinkedHashMap使用双向链表保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的.HashMap里面存入的键值对在取出的时候是随机的,

 

也可以在构造时 用带参数,按照应用次数排序。在遍历的时候会比HashMap慢,不过有种情况例外,当HashMap容量很大,实际数据较少时,遍历起来可能会比 LinkedHashMap慢,因为LinkedHashMap的遍历速度只和实际数据有关,和容量无关,而HashMap的遍历速度和他的容量有关。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics