Java中HashMap如何工作的?

JavaHashMap工作原理 HashMapJava 集合框架中一个非常重要的类,它实现了 Map 接口,用于存储键值对(key-value pairs)。其核心特点是基于哈希表实现,提供了平均时间复杂度为 O(1) 的基本操作。以上就是关于 JavaHashMap 的基本原理介绍,了解这些有助于更好地利用 HashMap 提升程序性能。值得注意的是,HashMap 不是线程安全的。若要在多线程环境中使用,可以考虑使用。包装 HashMap,或者使用。,后者提供了更好的并发支持。 阅读详情

How HashMap works in Java

How HashMap  works in Java
How HashMap works in Java or sometime how get method work in HashMap is common questions on Java interviews now days. Almost everybody who worked in Java knows about HashMap, where to use HashMap or difference between Hashtable and HashMap then why this interview question becomes so special? Because of the depth it offers. It has become very popular java interview question in almost any senior or mid-senior level Java interviews. Investment banks mostly prefer to ask this question and some time even ask to implement your own HashMap based upon your coding aptitude. Introduction of ConcurrentHashMap and other concurrent collections has also made this questions as starting point to delve into more advanced feature. let's start the journey.

Questions start with simple statement 


"Have you used HashMap before" or   "What is HashMap? Why do we use it “
Almost everybody answers this with yes and then interviewee keep talking about common facts about HashMap like HashMap accept null while Hashtable doesn't, HashMap is not synchronized, HashMap is fast and so on along with basics like its stores key and value pairs etc. This shows that person has used HashMap  and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow-up questions gets more detailed about fundamentals involved with HashMap in Java . Interviewer struck back with questions like

"Do you Know how HashMap works in Java” or "How does get () method of HashMap works in Java"
And then you get answers like I don't bother its standard Java API, you better look code on Java source or Open JDK; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object  to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic. If people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in Java HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge on how hashing works and how HashMap  works in Java. But this is just start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by day basis. Next question could be about collision detection and collision resolution in Java HashMap  e.g. 

"What will happen if two different objects have same hashcode?”
Now from here onwards real confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap  will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract  that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. Great this answer make sense though there are many collision resolution methods available this is simplest and HashMap in Java does follow this. But story does not end here and interviewer asks

"How will you retrieve Value object  if two Keys will have same hashcode?”
how HashMap works internally in JavaInterviewee will say we will call get() method and then HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object but then you need to remind him that there are two Value objects are stored in same bucket , so they will say about traversal in LinkedList until we find the value object , then you ask how do you identify value object because you don't  have value object to compare ,Until they know that HashMap  stores both Key and Value in LinkedList node or as Map.Entry they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap . Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashCode() and equals() or keys and values object in Java HashMap  which is pretty obvious because they are dealing with the hashcode() in all previous questions and equals() come in picture only in case of retrieving value object from HashMap in Java. Some good developer point out here that using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap  keys and improve performance of Java HashMap  by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.

Now if you clear this entire Java HashMap interview,  You will be surprised by this very interesting question " What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor ?". Until you know how HashMap  works exactly you won't be able to answer this question. If the size of the Map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Similar to other collection classes like ArrayList,  Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array. This process is called rehashing because it also applies hash function to find new bucket location. 

If you manage to answer this question on HashMap in Java you will be greeted by "do you see any problem with resizing of HashMap  in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap  in Java

So the answer is Yes there is potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java HashMap  doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap  in multi-threaded environment to interviewer :)

 
Few more question on HashMap in Java which is contributed by readers of Javarevisited blog  :
1) Why String, Integer and other wrapper classes are considered good keys ?
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety, If you can  keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.

2) Can we use any custom object as key in HashMap ?
This is an extension of previous questions. Ofcourse you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If custom object is Immutable than this will be already taken care because you can not change it once created.

3) Can we use ConcurrentHashMap in place of Hashtable ?
This is another question which getting popular due to increasing popularity of ConcurrentHashMap. Since we know Hashtable is synchronized but ConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced as Hashtable and can be used in place of it but Hashtable provide stronger thread-safety than ConcurrentHashMap. See my post difference between Hashtable and ConcurrentHashMap for more details.
 

Personally, I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap  questions has verified
  • Concept of hashing
  • Collision resolution in HashMap
  • Use of equals () and hashCode () and there importance in HashMap?
  • Benefit of immutable object?
  • Race condition on HashMap  in Java
  • Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions

How HashMap  works in Java
HashMap  works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.
Also HashMap  stores both key+value tuple in every node of linked list.

What will happen if two different HashMap  key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap .

In terms of usage Java HashMap is very versatile and I have mostly used HashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching HashMap and ConcurrentHashMap  comes as very handy there. You can also check following articles form Javarevisited to learn more about HashMap and Hashtable in Java :
JavaHashMap工作原理是什么? HashMap通过链表来处理这种冲突,将具有相同哈希码的元素存储在同一数组位置的链表中。当数组的填充度超过阈值(默认为数组容量的75%),HashMap会进行扩容,通常扩容为原来的两倍,并重新分配所有元素。当添加一个元素时,HashMap会使用哈希函数计算键的哈希码,然后用这个哈希码来决定元素在数组中的存储位置。当链表长度超过一定阈值(默认为8)时,链表会转换为红黑树,以改善在高哈希冲突情况下的性能。HashMap基于数组和链表的结构,数组用于存储元素,链表用于解决哈希冲突。 阅读详情

相关推荐

JAVA中的HashMap是如何工作

译自how-does-a-hashmap-work-in-java 大部分JAVA开发人员使用Maps,尤其是HashMaps。哈希映射是一个简单但是强大的存储和获取数据的方式。但是有多少开发人员知道HashMap内部是如何工作的吗?几年以前,我读了大量的java.util.HashMap源代码 (先是JAVA7后是JAVA8),为了对这个基本的数据结构有深入的了解。在这篇帖子中,我会介绍jav...

AhahaGe 3444

HashMap是如何工作

一、HashMapJAVA中的怎么工作的? 基于Hash的原理 二、什么是哈希? 最简单形式的hash,是一种在对任何变量/对象的属性应用任何公式/算法后, 为其分配唯一代码的方法。 一个真正的hash方法必须遵循下面的原则 哈希函数每次在相同或相等的对象上应用哈希函数时, 应每次返回相同的哈希码。换句话说, 两个相等的对象必须一致地生成相同的哈希码。 Java 中所有的对象都有...

javafirst 945

JAVAJava中的HashMap工作原理是什么?

hashmap是一个key-value键值对的数据结构,从结构上来讲在jdk1.8之前是用数组加链表的方式实现,jdk1.8加了红黑树,hashmap数组的默认初始长度是16,hashmap数组只允许一个key为null,允许多个value为null hashmap的内部实现,hashmap是使用数组+链表+红黑树的形式实现的,其中数组是一个一个Node[]数组,我们叫他hash桶数组,它上面存放...

5858

HashMapjava中是怎么工作

大多数人都会同意,HashMap是现在面试题目中最受欢迎的问题,我和我的同事讨论过几次,确实很有帮助,现在,我继续和大家讨论。 在讨论前我假设对HashMap的内在工作原理感兴趣,并且已经理解了基本的概念,所以我跳过了这部分,如果你对概念性的东西一无所知,那么请参照官方的java doc 。 一句话来总结这个答案 如果任何人问我描述一下:”HashMap是如何工作的?”我会简单的回答:“基于

maoyeqiu的专栏 1350

HashMap如何在JAVA工作

大多数JAVA开发人员都在使用Maps,尤其是HashMaps。HashMap是一种简单但功能强大的存储和获取数据的方式。但是,有多少开发人员知道HashMap在内部如何工作?几天前,我阅读了java.util.HashMap的大部分源代码(从Java 7到Java 8),以便对这种基本数据结构有深入的了解。在本文中,我将解释java.util.HashMap的实现,介绍JAVA 8实现中的新增功能,并讨论使用HashMaps时的性能,内存和已知问题。 内部存储器 JAVA HashMap类实现接.

weixin_40478901的博客 2670

javahashmap_HashMap如何在Java工作

javahashmap 面试中最常见的问题是“ HashMap如何在Java工作”,“ HashMap的获取和放置方法如何在内部工作”。 在这里,我试图通过一个简单的示例来解释内部功能。 而不是通过理论,我们将首先从示例开始,以便您可以更好地理解,然后我们将了解get和put函数如何在Java工作。 让我们举一个非常简单的例子。 我有一个Country类,我们将使用Country类对象...

最佳 Java 编程 243

Java HashMap工作原理

面试的时候经常会遇见诸如:“java中的HashMap是怎么工作的”,“HashMap的get和put内部的工作原理”这样的问题。本文将用一个简单的例子来解释下HashMap内部的工作原理。首先我们从一个例子开始,而不仅仅是从理论上,这样,有助于更好地理解,然后,我们来看下get和put到底是怎样工作的。 我们来看个非常简单的例子。有一个”国家”(Country)类,我们将要用Country对象

Java干货 1037

HashMap如何工作 - Java

大多数人应该会同意HashMap是现在面试最喜欢问的主题之一。我和同事常常进行讨论,并很有帮助。现在,我继续和大家讨论。 我假设你对HashMap的内部工作原理感兴趣,并且你已经知道了基本的HashMap使用,所以我跳过这部分。但如果HashMap的概念你觉得很新,那么参考官方 Java docs。 在继续之前,我强烈建议你阅读我以前的帖子:使用hashCode()和equals()方法 - Java 本文包括如下内容: 一句话回答 什么是Hashing? 关于Entry类 put()方法到底干了什么 g

bill的博客 217

HashMapJava内部如何工作

看一下这篇文章,解释HashmapJava中的工作方式,包括它如何计算存储桶的索引以及其他内部结构的工作方式。 在本文中,我们将了解HashMapJAVA中的内部工作方式。另外,我们将看看Java 8对Hashmap的内部工作进行了哪些更改以使其更快。 Java中的HashMap遵循哈希原理。它是一个数据结构,只要我们知道密钥,就可以在恒定的时间O(1)中存储并检索对象。在哈希中,哈希函数用于链接HashMap中的键和值。 Hashmap如何计算Java中存储桶的索引 要了解HashMapJava内部

weixin_46699878的博客 224

Java HashMap工作原理及实现

1.参考 (1)Java HashMap工作原理及实现 https://yikun.github.io/2015/04/01/Java-HashMap工作原理及实现/

ly969434341的专栏 577

Java中,HashMap是如何工作的?

Java中,HashMap是如何工作的?HashMap在Map.Entry静态内部类实现中存储key-value对。 HashMap使用哈希算法,在put和get方法中,它使用hashCode()和equals()方法。 当我们通过传递key-value对调用put方法的时候,HashMap使用Key hashCode()和哈希算法来找出存储key-value对的索引。 public V g

面向阳光的向日葵的专栏 1974

HashMap如何在Java内部工作

在本文中,我们将看到HashMap如何在Java内部工作。此外,我们还将了解Java 8对Hashmap的内部工作进行了哪些更改,以使其更快。 A HashMap用于存储键值对映射的映射。要了解关于HashMap的更多信息,请访问本文:Java中的HashMap Java中的HashMap工作在散列原则上。它是一种数据结构,允许我们存储对象并在恒定时间内检索对象O(1),前提是我们知道密钥。在散列...

weixin_39388918的博客 122

HashMap如何在Java工作

面试中最常见的问题是“ HashMap如何在Java工作”,“ HashMap的获取和放置方法如何在内部工作”。 在这里,我试图通过一个简单的示例来解释内部功能。 而不是理论,我们将首先从示例开始,以便您更好地理解,然后我们将了解get和put函数在Java中的工作方式。 让我们举一个非常简单的例子。 我有一个Country类,我们将使用Country类对象作为键,并使用其大写名称(字符...

最佳 Java 编程 213

理解JavaHashMap工作原理

Java中的HashMap使用散列来高效的查找和存储值。HashMap内部使用Map.Entry的形式来保存key和value, 使用put(key,value)方法存储值,使用get(key)方法查找值。 理解hashCode() Java中的hashCode()方法,是顶层对象Object中的方法,因此Java中所有的对象都会带有hashCode()方法。 在各种最佳实践中,都

Chenny的blog 568
上一篇: Java中如何重载equsals和hashCode方法,示例和提示
下一篇: Android-sdk r22.0.4 发布
儿大不由爷
博客等级 码龄23年 541粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值