This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value
why map is allowed as a value , but not as a key?
Taken out of context. That section in the doc discusses the requirement for keys to be immutable, and how a map adding itself will break since the map is changing. In context, those statements makes sense.
It is actually permissible i.e. java will not throw any runtime or compile time exception. BUT its not recommended. Actually the rule applies for any Mutable Key object as pointed out by Henry.
I think every thing will be clear with a small example as follows:
and the output is as follows :
Hope that answers your doubts naveen
A TubeBulb May light slowely... But it lights the Brightest..
No. Apparently you missed the word "itself" in what you read, since the example you posted is not an example of a map containing itself as a key.
Joined: Jul 09, 2009
Paul , you are very right. And as obvious from the example , In general we should avoid making a Map a key, because when that key's value changes, it messes everything up.
So if the map contains itself as a key. I guess it will mess up things more :O
So my 2 cents would be in general : Always Avoid Maps as keys (i.e. if you ever intend to change it's value in future )
But i am not very sure about the Immutable Maps question. I am not very clear with the concept. But what is know is that, you cant change it ever :O. So should not be a problem i guess.