Java集合(三、Hashtable)

Hashtable源码实现上和HashMap基本上没什么大的差别,有兴趣可以查看HashMap一章了解下。

要点总结

1.Hashtable不支持key或者value为null的情况,HashMap和LinkMap可以支持:

并非由于啥特别的原因,只是Hashtable源码进行put操作时,判断null抛出了NullPointerException异常,如下:


```
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {   //判断value为null则抛出NullPointerException异常              
            throw new NullPointerException(); 
        }
    
        // Makes sure the key is not already in the hashtable.
        HashtableEntry<?,?> tab[] = table;
        int hash = key.hashCode();  //key为null时,则此处为抛出NullPointerException异常
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        HashtableEntry<K,V> entry = (HashtableEntry<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;
    }
```

而HashMap则对null进行了容错:


```
    public V put(K key, V value) {
        //这边并没对value进行Null的判断
        return putVal(hash(key), key, value, false, true);
    }

    static final int hash(Object key) {
        int h; //如下,key为null值则默认hash返回0,
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
```
复制代码

2.Hashtable是线程安全的,HashMap和LinkHashMap非线程安全:

主要是Hashtable在数据存取等关键接口上使用了synchronized来达到线程同步的效果:

public synchronized V get(Object key){...}
public synchronized V put(K key, V value) {...}
public synchronized V put(K key, V value){...}
public synchronized void putAll(Map<? extends K, ? extends V> t) {...}
public synchronized V remove(Object key){...}
public synchronized void clear(){...}
public synchronized boolean contains(Object value){...}
public synchronized boolean containsKey(Object key){...}
...
复制代码

等等一堆和数据写入和读取相关的接口都用synchronized简单实现了线程同步,

3.多线程并发的处理效率上Hashtable因为synchronized机制要比HashMap和LinkHashMap低很多,但至少保证了线程安全,不用再手动去增加线程安全的操作

4.Hashtable本身已经快被淘汰,并不推荐使用,查看该类的源码注释:

 * If a thread-safe implementation is not needed, it is recommended to use
 * {@link HashMap} in place of {@code Hashtable}.  If a thread-safe
 * highly-concurrent implementation is desired, then it is recommended
 * to use {@link java.util.concurrent.ConcurrentHashMap} in place of
 * {@code Hashtable}.
复制代码

意思是,如果不需要线程安全,请使用类似HashMap。 如果需要较高的并发线程安全要求,请使用ConcurrentHashMap,该类效率会比Hashtable高很多。

扫描关注公众号获取更多内容

猜你喜欢

转载自blog.csdn.net/a8082649/article/details/81836317