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));
    }
   }
}

运行结果以下:java

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

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

再普及下:app

java为数据结构中的映射定义了一个接口java.util.Map;它有四个实现类,分别是HashMap Hashtable LinkedHashMap 和TreeMap.post

Map主要用于存储健值对,根据键获得值,所以不容许键重复(重复了覆盖了),但容许值重复this

 


Hashmapspa

   是一个最经常使用的Map,它根据键的HashCode值存储数据,根据键能够直接获取它的值,具备很快的访问速度,遍历时,取得数据的顺序是彻底随机的。 HashMap最多只容许一条记录的键为Null(若是建是null存在数组的第一个位置);容许多条记录的值为 Null;HashMap不支持线程的同步,即任一时刻能够有多个线程同时写HashMap;可能会致使数据的不一致。若是须要同步,能够用 Collections的synchronizedMap方法使HashMap具备同步的能力,或者使用ConcurrentHashMap。线程

  默认初始化的时候是16个数组的大小,并且增加是成倍的增加。code

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }

 

Hashtable对象

  与 HashMap相似,它继承自Dictionary类,不一样的是:它不容许记录的键或者值为空;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,所以也致使了 Hashtable在写入时会比较慢。

   默认初始化的时候是11个数组的大小,并且增加是old*2+1

    public Hashtable() {
        this(11, 0.75f);
    }

 

LinkedHashMap

   是HashMap的一个子类,保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先获得的记录确定是先插入的.也能够在构造 时用带参数,按照应用次数排序。在遍历的时候会比HashMap慢,不过有种状况例外,当HashMap容量很大,实际数据较少时,遍历起来可能会比 LinkedHashMap慢,由于LinkedHashMap的遍历速度只和实际数据有关,和容量无关,而HashMap的遍历速度和他的容量有关。

TreeMap

  实现SortMap接口,可以把它保存的记录根据键排序,默认是按键值的升序排序,也能够指定排序的比较器,当用Iterator 遍历TreeMap时,获得的记录是排过序的。

 

  一 般状况下,咱们用的最多的是HashMap,在Map 中插入、删除和定位元素,HashMap 是最好的选择。但若是您要按天然顺序或自定义顺序遍历键,那么TreeMap会更好。若是须要输出的顺序和输入的相同,那么用LinkedHashMap 能够实现,它还能够按读取顺序来排列.

相关文章
相关标签/搜索