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
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.
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.