Also, Set's add() method returns a boolean, which is "true if this set did not already contain the specified element."
posted 8 years ago
While we're at it, let's go back to the original question. The situation for Set seems rather overly-described at this point. But what about Maps?
Aside from using containsKey() as marc described, you can test just after performing a put(), by looking at the return value. If put() returns a non-null value, then that value was the old value in the map (which you've just replaced with the new value). If it returns a null, that either means that there was no entry for that key, or there was an entry, and the value of that entry was null. If the distinction between those last two scenarios seems unnecessarily confusing, I agree. There is never any good reason to put() a null value into a map. If you ever encounter this in the real world, find out who did it, and have them killed. Or fired. Whichever seems easier.
Also, ConcurrentHashMap has a putIfAbsent() method. This seems like a useful concept that should have been put into Map (and Set) in the first place, but wasn't. Too bad. Still, I recommend this, especially if you are using a Map in a multi-threaded environment.