aspose file tools
The moose likes Java in General and the fly likes Benefit Of Using Key as Object In HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Benefit Of Using Key as Object In HashMap" Watch "Benefit Of Using Key as Object In HashMap" New topic
Author

Benefit Of Using Key as Object In HashMap

RamandeepS Singh
Ranch Hand

Joined: Aug 25, 2009
Posts: 60
Hello

As I came to know that we can Use object as key in java

as i Implemented this and it works ...
But didnt came to know the benefit of using key as object
Means where n when to use Objects as key in HashMap

OutPut : Firstly it prints
[test,test1]
and
then NULL

but if i use String as below


OutPut : Firstly it prints
[test,test1]
and
then [test,test1,test2]
Conclusion : That if we use object as key object can not be alter.....
but whats its benefit

When shud i use

Please explain with example

Thanks and regards
Ramandeep Singh
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Please UseCodeTags when posting code or configuration. Unformatted code and configuration is unnecessarily difficult to read. You can edit your post by using the button.
Means where n when to use Objects as key in HashMap

Always, because you *have* to: map keys and values are *always* object references.

See the java.util.Map Javadocs for what happens if you use a mutable object as a key; particularly the part that begins:
Note: great care must be exercised if mutable objects are used as map keys.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19232

RamandeepS Singh wrote:When shud i use

Please UseRealWords: "should", not "shud".

Also, the tag is [code], not [javadoc]. I've modified it for you and split it into two code blocks.


Right, now to the answer. HashMap uses the hash code of the key to find the appropriate bucket to put the object in. If you then modify the object in such a way that its hash code changes, if you use that object to look for the value the HashMap will look in the wrong bucket. It can't find the key in there, so it returns null. In short, you should not use mutable objects as keys for any map, unless:
a) the hash code itself is immutable (e.g. you can change the object, just not its hash code).
b) you make very, very sure that you don't change the object while it's a key in the map.

This is why String, Integer and Long are favourites as map keys - they are immutable; once created, the hash code will never change anymore.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Benefit Of Using Key as Object In HashMap
 
Similar Threads
Maps
Question from John Meyer's Mock
Doubt regarding HashMap Example
Please explain the last output of this example from kathy sierra book
working of map?