1. 程式人生 > >HashMap和Hashtable存放null

HashMap和Hashtable存放null

war read ash nal style () exce point entry

Hashmap是可以放key為null的,Hashtable不能放key為null。hashtable放key為null會報空指針異常

1. hashmap put方法源碼

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

2.hashtable 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(); 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; }

HashMap和Hashtable存放null