Hashtable

Posted mike_chang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hashtable相关的知识,希望对你有一定的参考价值。

Hashtable也采用的链地址法

package java.util;

import java.io.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.BiFunction;
import sun.misc.SharedSecrets;

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {
    
    public Hashtable() {
        this(11, 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;
        /* new Hashtable时直接创建Hashtable
         * 
         * new Hashtable时我们输入的容量是多少就会创建多大的数组
         * 布HashMap会转换为2的几次幂
         */
        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;
        int hash = key.hashCode();
        // hashtable的哈希方法还用到了取模运算
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            // 如果hash和key都相同,覆盖value的值
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }    
    // get方法也是同步的
    @SuppressWarnings("unchecked")
    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的主要内容,如果未能解决你的问题,请参考以下文章

HashMap和HashTable

HashMap 和 HashTable差别

PHP源代码分析:Zend HashTable详解

java源码之HashMap和HashTable的异同

Hashtable与ConcurrentHashMap入门——简单使用

HashTable源代码剖析