HashMap和HashTable

HashMap

  • 基于 哈希表 的 Map 接口的实现类
  • key 允许为 null , value 也允许为 null
  • 不保证映射的顺序,特别是它不保证该顺序恒久不变

HashTable

Map接口的的实现类

  • 实现一个哈希表,该哈希表将键映射到相应的值
  • Hashtable 的 key 和 value 都不能为 null
  • 几乎所有的方法都是线程安全的
  • Properties类继承了HashMap。

HashMap 和 Hashtable 的相同点
1、内部都是基于 哈希表 存储数据(内部都有数组table,HashMap是Node<K,V>[] table),HashTable是Entry<?,?>[] table。

HashMap:

   /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

该表在首次使用时初始化,并根据需要调整大小。分配时,长度总是2的幂(HashMap为了加快hash的速度)。(我们也允许在某些操作中允许长度为零)。用transient关键字标记的成员变量不参与序列化过程。

HashTable:

   /**
     * The hash table data.
     */
    private transient Entry<?,?>[] table;

2、HashMap 和 Hashtable 的迭代器 都是 快速失败 ( fail-fast ) 的
HashMap 和 Hashtable 的区别
1、用来确定元素在哈希表中的位置的方式不同

HashMap:
     HashMap 根据 key.hashCode() 重新计算一个值:

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
static final int hash( Object key ) {
           int h;
            return (key == null) ? 0 : ( h = key.hashCode() ) ^ ( h >>> 16 );
}

     然后再根据这个值来确定元素在哈希表中的位置:

部分源码

复制代码
  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
..................................
复制代码
源码if ((p = tab[i = (n - 1) & hash]) == null)转换:
            tab[i] = newNode(hash, key, value, null);
 int n = table.length ;
 int hash = hash( key ) ;
 table[ ( n - 1) & hash ] = newNode( hash, key, value, null ) ; // 不是源码

Hashtable:

public synchronized V put(K key, V value) {
        //确保value 不能为空
        if (value == null) {
            throw new NullPointerException();
        }

        // 确保key不在哈希表
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
......................................
  int hash = key.hashCode(); // key 必须不能为 null,不然抛出空指针异常
  int index = (hash & 0x7FFFFFFF) % tab.length;

直接使用对象的hashCode。

2、HashMap 不支持线程安全的 ( 所有的方法都没有 synchronized 修饰 )。
     Hashtable 支持线程安全的 ( 几乎所有的方法都被 synchronized 修饰 )。

3、初始容量大小和每次扩充容量大小的不同

HashMap:

   
   /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
   /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

   /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
             // 超过最大值就不再扩充了,就只好随你碰撞去吧
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
             // 没超过最大值,就扩充为原来的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
         // 计算新的resize上限
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 把每个bucket都移动到新的buckets中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

默认初始容量2^4(16) 和默认加载因子 (0.75),每次扩充为原来的2倍。如果指定容量会根据所给的初始值扩充为刚超过initialCapacityde的2的幂次方数。例如指定容量是20,则实际容量是2^5(32)。

Hashtable:

   /**
     * Constructs a new, empty hashtable with a default initial capacity (11)
     * and load factor (0.75).
     */
    public Hashtable() {
        this(11, 0.75f);
    }
   /**
     * Constructs a new, empty hashtable with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hashtable.
     * @param      loadFactor        the load factor of the hashtable.
     * @exception  IllegalArgumentException  if the initial capacity is less
     *             than zero, or if the load factor is nonpositive.
     */
    public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }
   /**
     * Increases the capacity of and internally reorganizes this
     * hashtable, in order to accommodate and access its entries more
     * efficiently.  This method is called automatically when the
     * number of keys in the hashtable exceeds this hashtable's capacity
     * and load factor.
     */
    @SuppressWarnings("unchecked")
    protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;

        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }

HashTable默认的初始大小为11,之后每次扩充为原来的2n+1。如果指定容量就是所指定的容量。

次要的区别:
4、父类不同: Hashtable 的 父类 Dictionary ,而 HashMap 的父类是 AbstractMap。
5、对 键集、值集、键值对集 的处理方式不同:
     HashMap 和 Hashtable 都具有:
            Set<K>    keySet()  返回所有的 key 组成的 Set 集合
           Collection<V>    values() 返回所有的 value 组成的 Collection 集合
           Set<Map.Entry<K,V>>    entrySet() 返回所有的 entry 对应的 Set 集合
    Hashtable 还具有:
            Enumeration<K>    keys()  返回此哈希表中的键的枚举
            Enumeration<V>    elements()   返回此哈希表中的值的枚举
6、因为 Hashtable 是线程安全的,因此 在 单线程环 境下比 HashMap 要慢。

7、HashMap允许存在一个为null的key,多个为null的value 。Hashtable的key和value都不允许为null。

8、HashMap把Hashtable的contains方法去掉了,改成containsValue和containsKey。 Hashtable则保留了contains,containsValue和containsKey三个方法,其中contains和containsValue功能相同。

 不推荐使用Hashtable 的原因

1、单线程中,无需做线程控制,运行效率更高

2、在多线程中,synchronized会造成线程饥饿,死锁,可以用ConcurrentHashMap替代

Hashtable和ConcurrentHashMap

1、它们都可以用于多线程的环境

2、但是当Hashtable的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间。

3、因为ConcurrentHashMap引入了分割(segmentation),不论它变得多么大,仅仅需要锁定map的某个部分,而其它的线程不需要等到迭代完成才能访问map。

4、简而言之,在迭代的过程中,ConcurrentHashMap仅仅锁定map的某个部分,而Hashtable则会锁定整个map。

HashMap工作原理

  • HashMap基于hashing原理,通过put()和get()方法储存和获取对象。
  • 当将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算hashcode,让后找到bucket位置来储存Entry对象。
  • 当获取对象时,通过键对象的equals()方法找到正确的键值对,然后返回值对象。
  • HashMap使用链表来解决碰撞问题,当发生碰撞了,对象将会储存在链表的下一个节点中。 HashMap在每个链表节点中储存键值对对象。
  • HashMap是在桶中储存键对象和值对象,作为Map.Entry。这一点有助于理解获取对象的逻辑。

牛客网笔试题

1、在Java中,关于HashMap类的描述,以下错误的是

正确答案: B  

A、HashMap使用键/值得形式保存数据

B、HashMap 能够保证其中元素的顺序

C、HashMap允许将null用作键

D、HashMap允许将null用作值

 2、有关hashMap跟hashTable的区别,说法正确的是?

正确答案: A B C D  

A、HashMap和Hashtable都实现了Map接口

B、HashMap是非synchronized,而Hashtable是synchronized

C、HashTable使用Enumeration,HashMap使用Iterator

D、Hashtable直接使用对象的hashCode,HashMap重新计算hash值,而且用与代替求模

 3、HashMap和HashTable的描述,错误的是?

正确答案: D  

A、他们都实现了Map接口。

B、HashMap非线程安全,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap就必须为之提供额外同步。

C、HashMap允许将null作为一个entry的key或者value,而Hashtable不允许。

D、通过contains方法可以判断一个对象是否存在于HashMap或者Hashtable中。

4、线程安全的map在JDK 1.5及其更高版本环境 有哪几种方法可以实现?

正确答案: C D

A、Map map = new HashMap()

B、Map map = new TreeMap()

C、Map map = new ConcurrentHashMap();

D、Map map = Collections.synchronizedMap(new HashMap());

解析:

  • HashMap,TreeMap 未进行同步考虑,是线程不安全的。
  • HashTable 和 ConcurrentHashMap 都是线程安全的。区别在于他们对加锁的范围不同,HashTable 对整张Hash表进行加锁,而ConcurrentHashMap将Hash表分为16桶(segment),每次只对需要的桶进行加锁。
  • Collections 类提供了synchronizedXxx()方法,可以将指定的集合包装成线程同步的集合。比如,

    List  list = Collections.synchronizedList(new ArrayList());

    Set  set = Collections.synchronizedSet(new HashSet());

推荐博客链接

https://www.cnblogs.com/liu-eagles/p/9059931.html

https://blog.csdn.net/gaopu12345/article/details/50831631

转载请于明显处标明出处

https://www.cnblogs.com/AmyZheng/p/9401198.html

posted @ 2018-08-01 16:23  AmyZheng  阅读(439)  评论(0编辑  收藏  举报