码迷,mamicode.com
首页 > 其他好文 > 详细

HashTable源码解析

时间:2020-03-21 12:46:07      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:creates   使用   with   remove   final   inter   shc   run   方法   

1、存储结构

    private static class Entry<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Entry<K,V> next;

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

    }

 

2、属性

    // Hashtable保存数据的数组
    private transient Entry<?,?>[] table;
    // hashtable的容量
    private transient int count;
    // 阈值
    private int threshold;
    // 负载因子
    private float loadFactor;
    // 结构性修改
    private transient int modCount = 0;

 

3、构造方法

//无参构造方法
    public Hashtable() {
        //默认容量是11,默认装载因子是0.75
        this(11, 0.75f);
    }
    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }
    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);
    }

 

3、添加(修改)

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

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        //根据key生成hash值
        int hash = key.hashCode();
        //通过hash值,找到存储的位置
        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;
            }
        }
        //如果table中不存在指定的key-value对,那么插入到链表首部
        addEntry(hash, key, value, index);
        return null;
    }    
    //将key-value对插入到链表首部
    private void addEntry(int hash, K key, V value, int index) {
        modCount++;

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

扩容:

    protected void rehash() {
        //记录旧的容量
        int oldCapacity = table.length;
        //记录旧的table
        Entry<?,?>[] oldMap = table;

        //扩容2倍加一,2N+1
        int newCapacity = (oldCapacity << 1) + 1;
        //不能让新table的容量超过了约定的最大值
        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;
         //将旧table中的值转移到新table中
        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;
            }
        }
    }        

 

4、删除

public synchronized V remove(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>)tab[index];
        for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                modCount++;
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    tab[index] = e.next;
                }
                count--;
                V oldValue = e.value;
                e.value = null;
                return oldValue;
            }
        }
        return null;
    }

 

 

5、查找

    public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
            }
        }
        return null;
    }

 

HashTable源码解析

标签:creates   使用   with   remove   final   inter   shc   run   方法   

原文地址:https://www.cnblogs.com/buhuiflydepig/p/12538466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!