how hashmap works in java - how to do in javahow to do in java

Upload: nitinrockz

Post on 02-Jun-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    1/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/

    Most of you will agree that HashMapis most favorite topic for discussion in interviews now-a-days. I have gone through several discussions with my colleagues time to time and it reallyhelped. Now, I am continuing this discussion with you all.

    I amassuming that if you are interested in internal working of HashMap, you already knowbasics of HashMap, so i am skipping that part. But if you are new to concept, follow official

    javadocs.

    Before moving forward, i will highly recommend reading my previous post : Working withhashCode and equals methods in java

    Sections in this post

    1) Single statement answer

    2) What is Hashing

    3) A little about Entry class

    4) What put() method actually does

    5) How get() methods works internally

    6) Key Notes

    Single statement answer

    If anybody asks me to describe How HashMap works?, I simply answer: On principle ofHashing. As simple as it is. Now before answering it, one must be very sure to know at leastbasics of Hashing. Right??

    YOU ARE HERE: HOME > CORE JAVA > COLLECTIONS > HOW HASHMAP WORKS IN JAVA

    Howhashmap works in javaOCTOBER 9, 2012 | LOKESH | 123 COMMENTS

    Follow 2.6k +85 Recommend this on Google

    How To Do In Java

    http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.htmlhttp://docs.oracle.com/javase/6/docs/api/java/util/HashMap.htmlhttp://howtodoinjava.com/http://howtodoinjava.com/category/core-java/http://howtodoinjava.com/category/core-java/java-collection-framework/http://howtodoinjava.com/http://-/?-http://-/?-http://-/?-http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/http://-/?-http://howtodoinjava.com/author/lokeshgupta1981/http://-/?-http://-/?-http://howtodoinjava.com/category/core-java/http://-/?-http://-/?-http://-/?-http://howtodoinjava.com/http://howtodoinjava.com/category/core-java/java-collection-framework/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.htmlhttp://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    2/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 2

    What is Hashing

    Hashingin its simplest form, is a way to assigning a unique code for any variable/object afterapplying any formula/algorithm on its properties. A true Hashing function must follow thisrule:

    Hash function should return the same hash code each and every time, when function isapplied on same or equal objects. In other words, two equal objects must produce same hashcode consistently.

    Read more here : Working with hashCode() and equals() methods in java

    A little about Entry class

    A map by definition is :An object that maps keys to values. Very easy.. right?

    So, there must be some mechanism in HashMap to store this key value pair. Answer is YES.

    HashMap has an inner class Entry, which looks like this:

    Surely Entry class has key and value mapping stored as attributes. Key has been marked asfinal and two more fields are there: next and hash. We will try to understand the need of thesefields as we go forward.

    What put() method actually does

    Before going into put() methods implementation, it is very important to learn that instancesof Entry class are stored in an array. HashMap class defines this variable as:

    All objects in java inherit a default implementation of hashCode() function defined in Object

    class. This function produce hash code by typically converting the internal address of the object

    into an integer, thus producing different hash codes for all different objects.

    12345678

    staticclassEntry implementsMap.Entry{ finalK key; V value; Entry next; finalinthash; ...//More code goes here}

    http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/http://en.wikipedia.org/wiki/Hash_function
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    3/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 3

    Now look at code implementation of put() method:

    Lets note down the steps one by one:

    1) First of all, key object is checked for null. If key is null, value is stored in table[0] position.Because hash code for null is always 0.

    2) Then on next step, a hash value is calculated using keys hash code by calling itshashCode() method. This hash value is used to calculate index in array for storing Entryobject. JDK designers well assumed that there might be some poorly written hashCode()functions that can return very high or low hash code value. To solve this issue, theyintroduced another hash() function, and passed the objects hash code to this hash() functionto bring hash value in range of array index size.

    3) Now indexFor(hash, table.length)function is called to calculate exact index position for

    1234

    /*** The table, resized as necessary. Length MUST Always be a power of two.*/transientEntry[] table;

    123456789

    1011121314

    15161718192021222324252627

    282930313233

    /*** Associates the specified value with the specified key in this map. If the* map previously contained a mapping for the key, the old value is* replaced.** @param key* key with which the specified value is to be associated* @param value* value to be associated with the specified key* @return the previous value associated with key, or null* if there was no mapping for key. (A null return* can also indicate that the map previously associated* null with key.)*/

    publicV put(K key, V value) { if(key == null) returnputForNullKey(value); inthash = hash(key.hashCode()); inti = indexFor(hash, table.length); for(Entry e = table[i]; e != null; e = e.next) { Object k; if(e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); returnoldValue; }

    }

    modCount++; addEntry(hash, key, value, i); returnnull;}

  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    4/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 4

    storing the Entry object.

    4) Here comes the main part. Now, as we know that two unequal objects can have same hashcode value, how two different objects will be stored in same array location [called bucket].Answer is LinkedList. If you remember, Entry class had an attribute next. This attributealways points to next object in chain. This is exactly the behavior of LinkedList.

    So, in case of collision, Entry objects are stored in LinkedList form. When an Entry objectneeds to be stored in particular index, HashMap checks whether there is already an entry?? Ifthere is no entry already present, Entry object is stored in this location.

    If there is already an object sitting on calculated index, its next attribute is checked. If it isnull, and current Entry object becomes next node in LinkedList. If next variable is not null,procedure is followed until next is evaluated as null.

    What if we add the another value object with same key as entered before. Logically, it should

    replace the old value. How it is done? Well, after determining the index position of Entryobject, while iterating over LinkedList on calculated index, HashMap calls equals method onkey object for each Entry object. All these Entry objects in LinkedList will have similar hashcode but equals() method will test for true equality. If key.equals(k) will be true then bothkeys are treated as same key object. This will cause the replacing of value object inside Entryobject only.

    In this way, HashMap ensure the uniqueness of keys.

    How get() methods works internally

    Now we have got the idea, how key-value pairs are stored in HashMap. Next big question is :what happens when an object is passed in get method of HashMap? How the value object isdetermined?

    Answer we already should know that the way key uniqueness is determined in put() method ,same logic is applied in get() method also. The moment HashMap identify exact match for

    the key object passed as argument, it simply returns the value object stored in current Entryobject.

    If no match is found, get() method returns null.

    Let have a look at code:

    123

    /*** Returns the value to which the specified key is mapped, or {@code null}* if this map contains no mapping for the key.

  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    5/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 5

    Above code is same as put() method till if (e.hash == hash && ((k = e.key) == key ||key.equals(k))), after this simply value object is returned.

    Key Notes1. Data structure to store Entry objects is an array named tableof type Entry.2. A particular index location in array is referred as bucket, because it can hold the first

    element of a LinkedList of Entry objects.3. Key objects hashCode() is required to calculate the index location of Entry object.4. Key objects equals() method is used to maintain uniqueness of Keys in map.5. Value objects hashCode() and equals() method are not used in HashMaps get() and put()

    methods.6. Hash code for null keys is always zero, and such Entry object is always stored in zero index

    in Entry[].

    I hope, i have correctly communicated my thoughts by this article. If you find any differenceor need any help in any point, please drop a comment.

    Happy Learning !!

    Related Posts:1. How to design a good key for HashMap

    456789

    10111213141516171819202122232425

    26272829

    **

    * More formally, if this map contains a mapping from a key {@code k} to a* value {@code v} such that {@code (key==null ? k==null :* key.equals(k))}, then this method returns {@code v}; otherwise it returns* {@code null}. (There can be at most one such mapping.)**

    * A return value of {@code null} does not necessarily indicate that* the map contains no mapping for the key; it's also possible that the map* explicitly maps the key to {@code null}. The {@link #containsKey* containsKey} operation may be used to distinguish these two cases.** @see #put(Object, Object)*/publicV get(Object key) { if(key == null) returngetForNullKey(); inthash = hash(key.hashCode()); for(Entry e = table[indexFor(hash, table.length)]; e != null; e =

    Object k; if(e.hash == hash && ((k = e.key) == key || key.equals(k)))

    returne.value; } returnnull;}

    http://howtodoinjava.com/2013/05/02/how-to-design-a-good-key-for-hashmap/
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    6/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 6

    2. Popular HashMap and ConcurrentHashMap interview questions3. Difference between HashMap and a Hashtable4. Performance comparison of different ways to iterate over HashMap5. Core java interview questions series : Part 16. Working with hashCode and equals methods in java

    123 THOUGHTS ON HOW HASHMAP WORKS IN JAVA

    DECEMBER 4, 2014 AT 5:51 AMExcellent explanation about hashing, none other were explained clear like thz.

    NOVEMBER 25, 2014 AT 6:52 AM

    Very simplified explination. Thanx

    NOVEMBER 7, 2014 AT 7:48 AM

    Nice and easy way of explanation, Thanks Lokesh!

    OCTOBER 23, 2014 AT 8:56 AM

    Good explainationand things got even more clear with comments

    SEPTEMBER 11, 2014 AT 4:49 AM

    This was a really great explanation

    SEPTEMBER 6, 2014 AT 7:46 AM

    Excellent tutorial I have a ever come cross that explain the internals of hashMap indepth and in simple words.

    CORE JAVA HASHMAP INTERVIEW QUESTION

    suresh

    sumit

    manish

    pradeep

    Abhimanyu

    Salil

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-7959http://howtodoinjava.com/tag/core-java/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-13829http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-13456http://howtodoinjava.com/2012/10/09/working-with-hashcode-and-equals-methods-in-java/http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-13329http://howtodoinjava.com/tag/hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-8182http://howtodoinjava.com/2013/03/01/core-java-interview-questions-series-part-1/http://howtodoinjava.com/2013/06/14/popular-hashmap-and-concurrenthashmap-interview-questions/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-13730http://howtodoinjava.com/tag/interview-question/http://howtodoinjava.com/2014/06/06/difference-between-hashmap-and-a-hashtable/
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    7/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 7

    AUGUST 22, 2014 AT 4:30 AM

    hi Lokesh, just tell me hashmap internally uses overriding equals() andhashCode().is there any situation where we need to write these two methods in ourhashmap program ???or only hashmap internally uses it???

    AUGUST 21, 2014 AT 2:46 PM

    really hands up for ur explanation i understood after a long back this conceptclearly thanks a lot

    NOVEMBER 4, 2014 AT 3:33 PM

    Hands up 8-|

    AUGUST 18, 2014 AT 5:56 AM

    Hi LokeshI found below paragraph on blogspot.com for the same question.

    While rehashing, if two thread at the same time found that now HashMap needsresizing and they both try to resizing. on the process of resizing of HashMap, theelement in bucket which is stored in linked list get reversed in order during theremigration to new bucket because HashMap doesnt append the new element at tailinstead it append new element at head to avoid tail traversing. If race conditionhappens then you will end up with an infinite loop.

    Please explain above paragraph. I failed to understand below points 1. Why list is getting reversed while rehashing. I mean what advantage we got ?2. Why elements are getting added at front end of list ? Why not tail end ?

    AUGUST 16, 2014 AT 6:23 PMhii just want to know that looping through the hashmap would be faster or through afor loop. I think for loop but just need an expert opinion on this.

    AUGUST 16, 2014 AT 6:44 PM

    Find a comparison here:http://howtodoinjava.com/2013/04/01/performance-comparison-of-

    swekha

    mani

    Sushil Kumar

    Anshuman

    sidharth

    Lokesh

    http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-7239http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-6973http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-7016http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-6971http://howtodoinjava.com/http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-7212http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-13427
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    8/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/

    different-ways-to-iterate-over-hashmap/

    AUGUST 5, 2014 AT 1:48 PM

    The article is really helpful Lokesh.I have a querry,you said objects are stored in LinkedList in a single bucket. is it like thisK!V>K!V>null?Pkease clarify.

    AUGUST 5, 2014 AT 5:40 PM

    Yes, you are right where K!V == instance of Entry class.

    JULY 28, 2014 AT 6:05 AM

    Is it possible to write a program in which we can put all elements in same bucket.like overiding some of the methods..

    JULY 28, 2014 AT 7:14 AM

    Absolutely. Look at the sourcecode.

    public Object put(Object obj, Object obj1) is public so you can

    override it. It uses indexFor(i, table.length) method call for getting

    the index location. Pass two constants values in this function and it willreturn the same location everytime; means all elements in same bucket.But other operations does not seem so simple. You will need to override a lotof methods to work it properly.

    JUNE 30, 2014 AT 12:35 PM

    Hello Lokesh,

    Thanks for sharing this nice article. I have a small doubt or say disagreementregarding put method explanation here

    So, in case of collision, Entry objects are stored in LinkedList form. When an Entryobject needs to be stored in particular index, HashMap checks whether there isalready an entry?? If there is no entry already present, Entry object is stored in thislocation.

    vridhi

    Lokesh

    Ajay

    Lokesh

    Saurabh Chhajed

    http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-6351http://howtodoinjava.com/http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-5726http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-6360http://saurzcode.wordpress.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4726http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-5729
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    9/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 9

    If there is already an object sitting on calculated index, its next attribute is checked.If it is null, and current Entry object becomes next node in LinkedList. If nextvariable is not null, procedure is followed until next is evaluated as null.

    So, that for loop in the put will run on a LinkedList at a particular bucket index, andthe only purpose of that for loop is to identify if key already exists and if it is replacethat and return the old value.

    and if key doesnt exist it will invoke

    i.e it will add entry to the head of linkedlist.

    Hope you got my point, Please let me know if above explanation has some flaws ?

    JUNE 30, 2014 AT 12:54 PM

    Hi Saurabh, yes you are right. Correct wording should be added to head oflinkedlist. Thanks for suggesting this small but critical language change.

    JUNE 11, 2014 AT 4:10 PM

    Hi Lokesh,Your article is very informative. I just have one question.If the state of an object is changed, the hashCode of that object will be re-calculateand changed automatically or will stay same until calculated again explicitly?

    1234

    56789

    10111213141516171819

    publicV put(K key, V value) { if(key == null) returnputForNullKey(value); inthash = hash(key.hashCode());

    inti = indexFor(hash, table.length); for(Entry e = table[i]; e != null; e = e.next) { Object k; if(e.hash == hash && ((k = e.key) == key || key.equals(k)

    V oldValue = e.value; e.value = value; e.recordAccess(this); returnoldValue; } }

    modCount++; addEntry(hash, key, value, i); returnnull; }

    1 addEntry(hash, key, value, i);

    Lokesh

    Aditya

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4023http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4727http://howtodoinjava.com/
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    10/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 10

    JUNE 11, 2014 AT 6:49 PM

    It will change automatically

    SEPTEMBER 16, 2014 AT 9:23 PM

    Great care must be exercised if mutable objects are used as set* elements. The behavior of a set is not specified if the value of anobject* is changed in a manner that affects equals comparisons while the* object is an element in the set,,,,,,, Does the same not apply for Map

    JUNE 5, 2014 AT 1:55 PM

    Hi Lokesh,

    Its the best explanation I ever came across. I have a small doubt. You mentioned inone of your above notes:If they have different hashcodes, they may or may not be in same bucket. Anythingis possible. You see if there are 100 objects, all having different hashcodes. Will youneed a hashtable of size 100?? NO. you do not need. You can accommodate themin a hashtable of size 10 also. It means some of objects with different hashcodeswill come into single bucket..

    How is this implemented ? if there are 100 objects, all having different hashcodes,

    then how can they go on same/single bucket (Entry type arrays element) ???

    JUNE 5, 2014 AT 3:45 PM

    The reason is indexFor(hash, table.length) method which return the

    bucket position at last.

    MAY 27, 2014 AT 6:58 AMHi sir,Iam Having Small Doubt related to Map.Question is like,if hashmap found 2same keys,then it will override old value with the latest value .but before overridingwith new value,is it possible to take or collect the old value from hashmapsir.Correct me if iam Wrong.Thanks Venkata Sriram

    MAY 27, 2014 AT 7:15 AM

    Hi Venkata, Its really good question. And infact easy as well. If you go

    Lokesh

    Arpit Shah

    Bittoo

    Lokesh

    Venkata Sriram

    Lokesh

    http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-8615http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3769http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4025http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3916http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3918http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3767
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    11/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 1

    through java docs of HashMap the put() method is given as:

    public V put(K key, V value)Parameters:key key with which the specified value is to be associatedvalue value to be associated with the specified keyReturns:the previous value associated with key, or null if there was no mapping forkey. (A null return can also indicate that the map previously associated nullwith key.)

    It returns the old value associated with key; IF any. I quickly ran below linesto write an example:

    It outputs as:

    nullinitial value

    So, when you write the new value then it returns the initial value.

    MAY 27, 2014 AT 9:14 AM

    Thanks alot sir.

    MAY 15, 2014 AT 2:57 AM

    MAY 15, 2014 AT 6:47 AM

    NO. It uses keys equals() method. If keys are equal, simply value object isoverwritten.

    12

    3456

    publicstaticvoidmain(String[] args){

    HashMap map = newHashMap(); System.out.println(map.put("data", "initial value")); System.out.println(map.put("data", "new value"));}

    Venkata Sriram

    [email protected]

    1 Does HashMap use any SET collection to maintain uniqueness of keys ?

    Lokesh

    Adarsh S

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3771http://howtodoinjava.com/https://plus.google.com/+AdarshSluniahttp://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3407http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-3401
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    12/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 12

    APRIL 24, 2014 AT 8:52 AM

    Its very usefull articleI think if u explained with picture or image i would begreate.

    APRIL 24, 2014 AT 2:50 AM

    Rakesh ,

    What is important is not only the hashcode but the number of buckets(Entry tablearray element is called bucket).Depending on the size of HashMap ie the number ofbuckets, the objects hashcode , hash and indexFor function will try to put the objectin one of the buckets. In case of HashMap of size 16 only lower 4 bits of hash valueis considered and in case of size 32 lower 5 bits are considered for &(byte operator)in indexFor function.I have done analysis of the same.Please check this blog for a demo of what I have mentioned above. Lokesh , Pleasecorrect me if my understanding is wrong somewhere.

    http://ganeshrashinker.blogspot.in/

    APRIL 18, 2014 AT 9:39 AM

    Note: All objects in java inherit a default implementation of hashCode() functiondefined in Object class. This function produce hash code by typically converting theinternal address of the object into an integer, thus producing different hash codes

    for all different objects.

    I disagree to the above statement. It is simply not possible

    Lets say, I have an Employee class.

    ANd I create 1 trillion trillion different objects of Employee class.But HashCode range is limited to the size of Integer in java..

    So there will be 2 different objects, which will have same hashcodeSo thestatement youve given above, cannot be always appliedThough it can be strivedto do so.

    APRIL 18, 2014 AT 10:08 AM

    Hi Yogesh, there are other things to consider as well i.e. garbage collection.You will need a really big heap to store so many objects, and other objects tokeep them referenced so that GC should not claim them to free memory. I

    Ganesh Rashinker

    Yogesh Gandhi

    Lokesh

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2887http://javakafunda.blogspot.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2799http://ganeshrashinker.blogspot.in/http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2800http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2890
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    13/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/ 13

    am pretty sure that you will get OutOfMemoryError much before trying tocreate so many objects.Another argument can be that hashCode() comes into consideration onlywhen you store all these objects in hash backed collection such asHashMap. As HashMap uses fixed length array to store key-value pairs, thenthe array size will require a continuous memory location of really big size. Itwill again result in OutOfMemoryError.

    APRIL 15, 2014 AT 4:44 PM

    when i put three object a1,a2,a3 in the hash map how they store in table? my doubtis when i get a1 than no equals will call but i get a2 than equals call one times andwhen i get a3 than equals will call two time why and how???

    I have create class A and override equals that will return false and hashcode return1.

    APRIL 6, 2014 AT 11:52 AM

    very informative

    APRIL 2, 2014 AT 8:52 AM

    Hashmap values of existing keys getting overwritten upon using put to store a new

    key-value pair. how to prevent it?

    APRIL 2, 2014 AT 12:31 PM

    Keys are never overwitten. If a matching key exist, then value may beoverwritten.

    MARCH 19, 2014 AT 7:33 AM

    Excellent article. Keep up the good work.

    MARCH 15, 2014 AT 2:06 PM

    Hi Lokesh Nice Explaination. Could you please tell me what is the default size of theEntry[] table array?Thanks.

    Ravi

    Anup

    amol bagde

    Lokesh

    Ginu

    Vilas Paskanti

    Lokesh

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2225http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2409http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2643http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2407http://howtodoinjava.com/http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2432http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2281
  • 8/10/2019 How Hashmap Works in Java - How to Do in JavaHow to Do in Java

    14/14

    12/11/2014 How hashmap works in java - How To Do In JavaHow To Do In Java

    MARCH 15, 2014 AT 4:13 PM

    From source code of HashMap.java:

    The default initial capacity MUST be a power of two.static final int DEFAULT_INITIAL_CAPACITY = 16;

    JUNE 18, 2014 AT 3:12 AM

    I just have a question about rehashing , will it increase the size oftable array ?

    JUNE 18, 2014 AT 3:31 AM

    Absolutely yes, otherwise what could be advantage of re-hashing? Rehashing happens when map grows beyond a limit.

    MARCH 5, 2014 AT 7:32 PM

    Excellent Tutorial Lokesh

    Note:- In comment box, please put your code inside [java] ... [/java]OR [xml] ... [/xml]tagsotherwise it may not appear as intended.

    Sid

    Lokesh

    Raj Kumar

    http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2227http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-2108http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4105http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/comment-page-2/#comment-4104http://howtodoinjava.com/