On Aug 10, 1:10 am, JKid314159 <[email protected]> wrote:
> Hi Miga:
>
> I tried the following code instead of the system out print.
>  
>         // Retrieve an iterator to the hashset:
>         Iterator iter = hs.iterator();
>        
>         // Extract elements from iterator.  Note that the elements may not
>         // follow the order in which they are added to HashSet.
>         while(iter.hasNext())
>             {
>               System.out.print(iter.next());
>                iter.remove();
>              }
>        
> But it does not work!
Try this:

        // Display the HashSet
        System.out.println("Contents of myHashSet after adding
objects: " + myHashSet);

        // Remove one by one the objects from the set printing them
        for (Iterator<Object> it = myHashSet.iterator(); it.hasNext
();) {
            Object object = it.next();
            System.out.println("Removing object: " + object);
            it.remove();
        }

        // Check that the collection is empty now
        System.out.println("Contents of my HashSet after removing
objects:" + myHashSet);
    }

The println on a HashSet returns an array of the objects like this:
[Grade: 9.8 Name: Henry, Grade: 17.5 Name: Anna, 2, 5, 8, Second
string, First String]
provided that the toString method in the myOwnClass has been overrided
to print "Grade: " + valueofgrade + " Name: " + valueofname

You'll notice also that println on a hashset does exactly the same
work as an iterator on it, and println on each object retrieved by the
iterator. Hence, as an abysmally lazy programmer, I prefere to use
println on the HashSet (;-))


--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to