zoukankan      html  css  js  c++  java
  • HashMap和Hashtable存放null

    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;
        }
  • 相关阅读:
    隔行扫描 和 逐行扫描
    CSS3--关于z-index不生效问题
    vue与其他框架对比
    跨域(转)
    vue 事件修饰符(阻止默认行为和事件冒泡)
    vue 3.0新特性
    bash leetcode
    数据库
    css排版
    盒模型
  • 原文地址:https://www.cnblogs.com/luckygxf/p/7267899.html
Copyright © 2011-2022 走看看