In Java, Collection.add() returns a boolean which is true if the added element wasn't present in the set whereas Map.put() returns the value that was previously associated with the key (or null if there was none).
Is there any reason that aren't implemented the same way (e.g. both returning boolean)?
Best Answer
I assume you mean
Map.put
- because there is noMap.add
. But even if they had the same name - these methods behave differently enough to render any attempt to unify their interface meaningless.Look at the way
Collection.add
's return value's doc is worded:Now, the only valid reason for the collection to not change is if it's a set and the item is already in there(any other reason should throw), but that wording was chosen because it makes sense for all collections, without having to make special clauses for sets and not-sets.
But does it make sense for maps? Consider this:
Case 1 and 3 both return
true
, but they are very different - one is overriding an entry and the other adding a new one. So maybe case 1 should have returnedfalse
? But then it would have been the same as case 2, even though one is changing the map and the other doesn't...So, copying
Collection.add
's behavior toMap.put
makes no sense. How about copyingMap.put
's behavior toCollection.add
? What if we hadCollection.add
return the old value?I see several problems with that:
add
!What if we have a
TreeSet
with a custom comparator?This is not a problem with
Map
, because it's looking by the key, and is already forced to define what you get when you request for that key.It forces the collection to actually retrieve the value. What if the
Collection
implementation is a bloom filter? It now has to actually look for the object instead of doing a quick hash match. What if it's a wrapper around a database table? It now has to create an object that you already have!Of course,
Map
would have a similar problem - but at least there the old value is important, because you don't know what it is and it's going to disappear. But withCollection
? It's all cost and no gain...