Page 1 of 1
About Question enthuware.ocpjp.v8.2.1380 :
Posted: Mon Nov 30, 2015 1:03 pm
by mrmuiz
You can read
here that
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.
but I can successfully compile and run this
Code: Select all
Map<Map,String>map=new HashMap<>();
map.put(map,"");
Does this mean that it is sintactically allowed (it will compile) but semantically it won't work because of equals and hashCode methods are not well defined?
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Mon Nov 30, 2015 8:10 pm
by admin
Yes, that is correct. Compiler cannot know what exact object map variable points to at run time and it cannot execute the code of put method to determine that putting map as the key is not permitted, and that is why it permits the call at compile time.
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Thu Jan 11, 2018 9:35 am
by julianblk
Then shouldn't the first option read:
It is not permissible for a map to contain itself as a key.
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Thu Jan 11, 2018 9:56 am
by admin
In that case, it would be a correct option. As of now, it is an incorrect option. So I think it is ok.
HTH,
Paul.
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Thu May 23, 2019 7:52 am
by Ildar_S
Code: Select all
Map<Map, Integer> m = new HashMap<>();
m.put(m, 3);
System.out.println(m.size());
Compiles and runs successfully, shouldn't the first option be correct then?
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Thu May 23, 2019 10:49 am
by admin
From JavaDoc API description on Map:
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.
https://docs.oracle.com/javase/8/docs/a ... l/Map.html
Re: About Question enthuware.ocpjp.v8.2.1380 :
Posted: Thu May 23, 2019 10:55 am
by Ildar_S
Thank you.