I am a beginner in Java and do not understand what if(!s.add(a)) means in this code excerpt:
Set<String> s = new HashSet<String>(); for(String a:args) { if(!s.add(a)) System.out.println("Duplicate detected:"+a); } add is specified in the Collection interface to return a boolean indicating whether the addition was successful. From the Javadocs:
Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)
This code prints out a message if the addition was unsuccessful, which happens when there is a duplicate in the set.
if collection s already has item a, then the add method will return false. The ! is a "not" operator, turning that false into true. So, if the item is already in the collection, you will see the println result.
As others have answered, add returns a boolean indicating whether a has been added to the set. Its equivalent to
Set<String> s = new HashSet<String>(); for(String a:args) { if (s.contains(a)){ System.out.println("Duplicate detected:"+a); } else{ s.add(a); } } From the javadoc for the Set interface.
contains boolean contains(Object o) Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null :o.equals(e)).
The add method returns a boolean indicating whether or not the add succeeded. Might be clearer with indenting:
Set<String> s = new HashSet<String>(); for(String a:args) if(!s.add(a)) System.out.println("Duplicate detected:"+a); Or even better with braces:
Set<String> s = new HashSet<String>(); for(String a:args) { if(!s.add(a)) { System.out.println("Duplicate detected:"+a); } } The message is displayed if the add failed.
s.add(a) will only add a to the set if it is not already contained in the set (by equality). The add method returns true iff the operation causes the set to be modified.
hence if a was already in the Set, the add method would not add it again, therefore not modify the set, therefore return false.
Presented for your consideration:
import java.util.Set; import java.util.HashSet; public class s1 { public static final boolean DUPLICATE = false; public static void main( String[] args ) { Set<String> s = new HashSet<String>(); if (!s.add("Hello Bub")) System.out.println("Duplicate detected(1)"); if (s.add("Hello Bub") == DUPLICATE) System.out.println("Duplicate detected(2)"); } } Which seems clearer?