The Artima Developer Community
Sponsored Link

Java Answers Forum
Importance of implementing hashcode() method for Java classes that are used

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
sandeep mahendru

Posts: 1
Nickname: sandeepm
Registered: Jan, 2011

Importance of implementing hashcode() method for Java classes that are used Posted: Jan 2, 2011 3:12 PM
Reply to this message Reply
Advertisement
I thought of sharing an important concept of implementing the method hashCode(). Some of us might know the concept, but based on some of our internal discussions, I feel there is still some ambiguity/confusion in understanding the finer points around it.

I have attached a sample program from the Effective Java book, that explains the importance of this concept.

The example illustrates the primary concept that even if two Java objects are semantically equal because of the "equals" implementation, they can still generate two different keys.

******************************** Brief explanation of the example *********************************************************

Two equal phone number objects are created , and they represent the same phone number.
The first phone object is used as a key and a value is inserted into the map.
During the get operation, the second same phone number object is created and used as the key, the object returned is null.
Why is this?

The answer lies in the internal implementation of the HashMap class and the way it generates indices from keys and puts the value in the internal table. [Basically an internal associative array] .
I have attached a word document that explains these details.


The bottom line is that if you are making use of Java objects as keys into a HashMap, please ensure that it implements the hashcode() method.

Now , what is the best hashCode() implementation? For that please read the details from the Effective Java book on Chapter number 3, item 9.

Topic: RMI and JTable Previous Topic   Next Topic Topic: Virtual Machine Launcher

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use