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

HashMap和Hashtable存放null

时间:2017-08-01 14:43:16      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:zed   方法   log   blog   key   ble   []   table   point   

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

标签:zed   方法   log   blog   key   ble   []   table   point   

原文地址:http://www.cnblogs.com/luckygxf/p/7267899.html

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