Java - Why does Map.put() overwrite while Set.add() does not?
I am wondering what the rationale is behind having Java's Map.put(key, value)
method overwrite equivalently key'd values that are already in the collection, while Set.add(value)
does not overwrite a pre-existing equivalent value that is already in the collection?
Edit:
It looks like majority viewpoint is that objects in a set that evaluate to equality should be equal in every respect, thus it shouldn't matter if Set.add(Object) overwrites equivalently valued objects or not. If two objects evaluate to equality, bu开发者_开发问答t do in fact hold different data, then a Map-type collection is a more appropriate container.
I somewhat disagree with this veiwpoint.
Example: A set holding a group of "Person" objects. In order to update some information about that person, you might want to pass the set a new, updated, person object to overwrite the old, outdated person object. In this case, a Person would hold a primary key that identifies that individual and the set would identify and compare people based only on their primary keys. This primary key is part of the person's identity as opposed to an external reference such as a Map would imply.The Map
behavior allows changing the values associated with equivalent keys. That is a pretty common use case: a : b
becomes a : c
.
Yes, over-writing Set
contents with add
could change something (reference value) - but that seems like a pretty narrow use case (which can be accomplished anyways - always try to remove before adding: s.remove(o); s.add(o);
) relative to what one would be getting in most cases - nothing for cycles.
edit:
the one potential use I could see for that behavior, is having a constrained memory budget, lots of heavy-but-equivalent objects being created, and having references to different equal versions in various places, preventing garbage collection of the duplicate ones. Having run into that problem before, however, I don't think this behavior is even the best way to solve it.
In my opinion, there is no point in overwriting something in Set, since nothing will change.
However when you update a map, the key might be the same, but the value might be different.
Note that Map isn't actually so different... it may always change the value, but (at least in Sun's implementations) the key will remain the same even if later calls to put() use a different instance that compares as equal to the original.
I disagree with the premise of your question. Both Map and Set are abstract interfaces. Whether they overwrite or not is an implementation detail.
- an implementation of Map that does not overwrite.
- You could create a mutable singleton set - adding stuff to the set overwrites the existing singleton value.
精彩评论