M
MooMaster
There's probably a really obvious answer to this question, but my
GoogleFu fails me, and after looking @ (http://java.sun.com/javase/6/
docs/api/), (http://java.sun.com/docs/books/tutorial/collections/
interfaces/map.html), and comp.lang.java and this newsgroup for the
most obvious keywords, nothing came quickly enough.
I have a Map of keys and values. I want to update my map such that I
change the key via an operation on its associated values (for a lousy
example, every time I add a new value to the values list, make the key
the mean value). The Map.Entry Interface only provides a getKey()
method, so the only idiom I've been able to come up with is:
for(Map.Entry<K,V> entry : map.entrySet())
{
newKey = performOperation(entry.getValue());
map.put(newKey, entry.getValue());
map.remove(entry);
}
But the cautionary note in the Map Interface's API : "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."
seems to suggest that there's an in-place, easier way of doing this.
What's the best way?
GoogleFu fails me, and after looking @ (http://java.sun.com/javase/6/
docs/api/), (http://java.sun.com/docs/books/tutorial/collections/
interfaces/map.html), and comp.lang.java and this newsgroup for the
most obvious keywords, nothing came quickly enough.
I have a Map of keys and values. I want to update my map such that I
change the key via an operation on its associated values (for a lousy
example, every time I add a new value to the values list, make the key
the mean value). The Map.Entry Interface only provides a getKey()
method, so the only idiom I've been able to come up with is:
for(Map.Entry<K,V> entry : map.entrySet())
{
newKey = performOperation(entry.getValue());
map.put(newKey, entry.getValue());
map.remove(entry);
}
But the cautionary note in the Map Interface's API : "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."
seems to suggest that there's an in-place, easier way of doing this.
What's the best way?