On Dec 18, 1:44 pm, DHARMENDRAN GOVIND <dharmendr...@gmail.com> wrote:
> Hello,
>
> The below program has declared 2 variables of type Hashset and one of the
> statements is trying to load duplicate names into variable dup.
>
> Question: Doesn't add method of Set interface follow "no duplicate rule"?
> Then what is the point of having statement uniques.removeAll(dup); Please
> advice.
Actually this code does much more than you have observed.
>
> package sethashsetfinddup2;
>
> import java.util.HashSet;
> import java.util.Set;
>
> public class Main {
>
>     public static void main(String[] args) {
>
>         // Set up test data
>         String name[] = {
>             new String("Sang"),
>             new String("Shin"),
>             new String("Boston"),
>             new String("Shin")
>         };
>
>         Set uniques = new HashSet();
>         Set dups = new HashSet();
>
>         for (int i=0; i<name.length; i++)
>             if (!uniques.add(name[i]))
See the add method of HashSet: 
http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)
It returns a boolean that indicates if the element is already
contained in the HashSet or not.
Hence this method does two things:
first it adds the name to uniques, following the non duplicate rules,
that is it adds only once the "Shin" string.
Then combined with the following one:
>                 dups.add(name[i]);
it adds to dups the second string "Shin" (not necessary in this order)
to dups.
Hence you end up with uniques containing:
Sang, Shin, Boston
and dups containing:
Shin
>
>         // Remove items that duplicates
>         uniques.removeAll(dups);
And here, the code remove from uniques all the strings containing in
dups, that is it removes from uniques the Shin string; and you end up
with uniques containing:
Sang, Boston
>
That is, exactly what the Unique words says:

>         System.out.println("Unique words:    " + uniques);
And what the Duplicate words says:
>         System.out.println("Duplicate words: " + dups);
>     }
>
> }
>
> Regards
> Dharmendran

Just put a System.out.println just after the for loop to print uniques
and dups or run the code step by step with the debugger, it helps
understand what happens.


Michèle Garoche

-- 
To post to this group, send email to javaprogrammingwithpassion@googlegroups.com
To unsubscribe from this group, send email to 
javaprogrammingwithpassion+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en

Reply via email to