Question: Which of these statements concerning maps are true?
Answer: It is permissible for a map to contain itself as a key.
Example code that generates StackOverflowError at runtime...
Is still unclear for me.
Map<Map, String> m=new HashMap<Map, String>();
m.put(m, "this map");
This code compiles fine. Is the question referring to something else?
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that 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, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.
The run time behavior has changed in the recent versions of Java but the restriction is still there in the API.
If you like our products and services, please help us by posting your review here.