HashMap具有null作为关键字 [英] HashMap having null as key

查看:142
本文介绍了HashMap具有null作为关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMap 如何区分 null 0 作为关键。

按照此帖子 null 键的哈希码是 0 ,它是正确的吗?
如果是,那么它们应该在索引 0 的同一个桶中存在,并且 HashMap 但这不是 HashMap 的工作原理。



有人可以解释我吗?什么是 null的散列码 HashMap



示例代码:

  HashMap< Integer,String> map = new HashMap< Integer,String>(); 
map.put(null,abc);
map.put(0,xyz); //是否会覆盖null作为关键字的值?

System.out.println(map.get(null)); // abc
System.out.println(map.get(0)); // xyz


解决方案


是的,那么他们应该在索引0处进入同一个桶...


正确。


并且HashMap中应该有一个值


不正确。这两个键将会有一个分隔条目。这是通过 Map HashMap 规范来保证的;即javadocs ,每个不同的密钥都会有一个单独的条目。这个实现是符合规范的 。它的确如此。



在Java 8之前, HashMap 处理冲突是将所有条目散列到同一个存储桶中。 HashMap.get(key)逻辑将迭代相关存储区的链,查找与该键匹配的条目。 (在你的示例代码中,在 null Integer(0)键的链中会有单独的条目。)在Java 8中,它的工作原理与之相同,但是对于键全部实现 Comparable ,链条变得太长。在这种情况下,长链被转换为二叉树......这样一个 O(N)链扫描变成了一个 O(logN) 树形搜索。


How HashMap internally differentiate between null and 0 as key.

As per this post the hash code for null key is 0, Is it correct? If yes then both should go in same bucket at index 0 and there should be one value in the HashMap but this is not how HashMap works.

Can somebody explain me? what is the hash code for null key in HashMap?

Sample code:

HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(null, "abc");
map.put(0, "xyz"); // will it override the value for null as key?

System.out.println(map.get(null));  // abc
System.out.println(map.get(0));     // xyz

解决方案

If yes then both should go in same bucket at index 0 ...

Correct.

and there should be one value in the HashMap

Incorrect. There will be a separsate entry for the two keys. This is guaranteed by the Map and HashMap specification; i.e. the javadocs say that there will be a separate entry for each distinct key. The implementation is required to meet the specification ... and it does.

Prior to Java 8, the way that HashMap handles collisions is to chain together all of the entries that hash to the same bucket. The HashMap.get(key) logic will iterate the chain for the relevant bucket, looking for an entry that matches the key. (In your example code, there would be separate entries in the chain for the null and the Integer(0) keys.)

In Java 8, it works the same to start with, but there is an optimization for the case where the keys all implement Comparable and the chains get too long. In this case, the long chains are converted into binary trees ... so that an O(N) chain scan turns into an O(logN) tree search.

这篇关于HashMap具有null作为关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆