Reputation: 331
the documentation states Set cannot contain duplicates
however this code works fine:
Set<String> vmv = new TreeSet<String>();
vmv.add("a");
vmv.add("a");
System.out.println(vmv.toString());
I just added a duplicate. Can someone explain this.
Upvotes: 2
Views: 120
Reputation: 236004
Calling add()
twice with the same value won't add it a second time, check the returned boolean
and you'll see that the second time it was false
, or check the set's size to verify that it didn't change after the second time:
Set<String> vmv = new TreeSet<String>();
System.out.println(vmv.add("a")); // prints true
System.out.println(vmv.size()); // prints 1
System.out.println(vmv.add("a")); // prints false
System.out.println(vmv.size()); // prints 1
Upvotes: 5
Reputation: 198103
From the same page, further down:
The
add
method adds the specified element to the Set if it's not already present and returns a boolean indicating whether the element was added.
...which is exactly what it's doing. When you print the final set, you should only see one copy of the "duplicate" element.
Upvotes: 2