• Post Reply Bookmark Topic Watch Topic
  • New Topic

How Do We Know that We Add Duplicate to a Set and Add Duplicate Key to a Map  RSS feed

 
Natalie Kopple
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A set cannot have duplicates. And a map cannot have duplicate keys.

How do we know that we are adding duplicate to a set? And how do we know we are adding duplicate key to a map?

Thank you.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way is to test before adding by using Set's contains method, and Map's containsKey method.

(Also note that Set's add method returns a boolean, which is "true if this set did not already contain the specified element.")
 
Natalie Kopple
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much for your help.
 
Alex Hurtt
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The add(E) method in Set returns a boolean indicating whether or not the thing you passed in was already contained in the Set. If it was, add() will return false and not modify the Set.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, Set's add() method returns a boolean, which is "true if this set did not already contain the specified element."
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!