我的知识海洋

What are you following

  • 首页
  • 标签
  • 分类目录
  • 文章归档
  • 行路万里
  • 读书万卷
  • About Me

  • 搜索
面经 解决方案 操作系统 Java源码 开源 GSoC 哲学 中间件 回溯 链表 书 top 数据库 分布式 滑动窗口 配置 动态规划 前缀树 并查集 Redis 总结 年终总结 面试 算法基础

9.21 | HashMap 的key能不能为null ,map 的呢?

发表于 2022-09-21 | 分类于 学习 | 阅读次数 1266
# Java源码
开源活动及项目推荐
9.22 | 手写一个排他锁,当多线程运行时只有线程名字为指定名字的线程能获取到锁

Hashmap的key可不可以为null,map呢?

对于HashMap来说,可以存放null键和null值,而HashTable则不可以。

在hashmap中

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put(null,1);
        System.out.println(map.get(null));
    }
// 1

hashmap的get方法

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

hash()方法

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

这里直接判断了ket == null? 等于的话直接为零,这里相当于找了key = 0 的value。

Map

对于map来说,能不能存放null键和null值要看具体实现的方法。

对于HashTable:

    public static void main(String[] args) {
        Map map = new Hashtable();
        map.put(null,1);
        System.out.println(map.get(null));

    }

Exception in thread "main" java.lang.NullPointerException
	at java.util.Hashtable.put(Hashtable.java:465)
	at dailyExercise.test.thread.Rectangle.main(Rectangle.java:16)

Hashtable.put() 方法

    public synchronized V put(K key, V value) {
        // Make sure the value is not null
      // 限制了 value 也不能为null ,如果value 为null,则npe
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
      // key 不能为null 
        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;
    }

其他map集合类

对于Map里面的键和值是否可以为空的问题,答案是:不一定,具体要看map实现的是哪个类的方法。

# Java源码
开源活动及项目推荐
9.22 | 手写一个排他锁,当多线程运行时只有线程名字为指定名字的线程能获取到锁

  • 文章目录
  • 站点概览
erdengk

erdengk

91 日志
5 分类
24 标签
RSS
Github E-mail
Creative Commons
友链
  • 星球球友
  • Joey
  • 北松山(itwaix)-TP在职
  • JooKS' Blog-GSoC 2022 Mentor
  • Chever-John-Shein在职
  • 一堆网页小游戏
  • 飞鸟记
0%
© 2019 — 2026 erdengk
由 Halo 强力驱动
陕ICP备2021015348号-1
川公网安备 51011202000481号
轻点广告,请我喝水,非常感谢 (。・ω・。)ノ(*/ω\*)