68 java集合和泛型_18 _HashMap与HashTable的区别

本文详细对比了HashMap与HashTable的数据结构、线程安全性、初始化方式、哈希算法、扩容策略等关键特性,揭示了两者在Java集合框架中的设计哲学与应用差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HashMap

  1. 线程不安全
  2. 底层实现:数组+链表或者红黑树
  3. Node节点的定义(链表)
  4. 初始容量为16的原因
  5. put方法
//底层实现:数组+链表或者红黑树
//保存的数组,初始化16个
transient Node<K,V>[] table;
//为entrySet和value提供一个缓存
transient Set<Map.Entry<K,V>> entrySet;
//元素的数量
transient int size;
//初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//数组递增的策略 当size > capacity*loadFacotor的时候递增
final float loadFactor;


//Node节点的定义(链表)
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
}

//初始容量为16的原因
//hash算法,保证哈希值平均分布,只有当为16的时候才可以最大程度的保证平均分布
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

    
//put方法
//创建一个HashMap对象,并且设定它的加载因子为0.75(超过则扩容,)
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

static final float DEFAULT_LOAD_FACTOR = 0.75f;
//执行put方法
public V put(K key, V value) {
    //key通过hash算法计算一个index
        return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
    //第一次进入为null,所以执行初始化容器大小
        if ((tab = table) == null || (n = tab.length) == 0)
            //此时返回的就是初始化容器以后的大小即16
            n = (tab = resize()).length;
    	//计算下标,如果等于null,直接赋值
    	if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
    	else {
            //如果该数组刚好有值,则采用链表或者红黑树的方式添加数据节点
            Node<K,V> e; K k;
            //判断两个节点是否相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //判断当前节点是否属于红黑树节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //如果不是直接进行链表连接
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        //将当前节点的下一个节点设置为新的实体节点
                        p.next = newNode(hash, key, value, null);
                        //如果此时的节点容量为7那么将链表转换为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //判断新传入的实体和当前绑定节点的子节点是否相同,如果相同直接退出
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //进入这个子节点
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
    //修改次数
        ++modCount;
    //查看当前容器的容量是否大于threshold ,如果大于增加数组容量为原来的一倍
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
}
    
    //初始化容器大小
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
    	//旧容量为0
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
    	int oldThr = threshold;
    //设置当前容器的递增为0
        int newCap, newThr = 0;
    //此时的oldCap=0 , newThr = 0 直接else执行
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //扩容,将数组的容量和扩容因子变为原来的一倍
            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
            //初始化容器为默认16
            newCap = DEFAULT_INITIAL_CAPACITY;
            //初始化阙值
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        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;
}

HashTable

  1. HashTable也是基于哈希表实现,和HashMap不同的是HashTable是线程安全的。
  2. 底层实现:哈希表+链表
  3. Hash函数
  4. 初始化。在构造方法中初始化。初始化指为11
  5. put方法
//底层实现:哈希表+链表
private transient Entry<?,?>[] table;//存储数组
private transient int count;//容器中数据多少
private int threshold;//容器容量达到次数以后进行修改
private transient int modCount = 0;//修改次数

//Hash函数 

        int hash = key.hashCode(); //在这两行 
        int index = (hash & 0x7FFFFFFF) % tab.length; //在这两行 
        
//初始化。在构造方法中初始化。初始化指为11
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);
}

//put方法
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
    	//hash函数计算一个index
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }
//增加实体
private void addEntry(int hash, K key, V value, int index) {
        Entry<?,?> tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
        modCount++;
    }

HashMap与HashTable的区别

对比项HashTableHashMap
底层时间哈希表+链表哈希表+链表+红黑树
初始化时间及大小构造方法初始化,大小为11put方法初始化,大小为16
线程安全安全不安全
Hash值直接使用了hashcode重新计算
扩容二倍+1二倍
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悬浮海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值