Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Please help, how to implement hasNext() and next() of a HashSet iterator?

800965Jul 27 2011 — edited Jul 29 2011
Hi guys,

Can someone help me out with this? I'm struggling to write an iterator (the hasNext() and next() methods) for a SimpleHashSet class and I keep failing. I have a basic unit test, which goes like this:
@Test
    public void testIterator() {
        SimpleHashSet<String> instance = new SimpleHashSet<String>();
        
        assertTrue(instance.iterator() != null);
        
        Iterator<String> it = instance.iterator();
        
        assertFalse(it.hasNext()); //Should return false on an empty HashSet
                
        assertTrue(it.next() == null); //Should return null on an empty HashSet
        
        instance.add("First");
        instance.add("Second");
        
        assertTrue(it.hasNext()); // Return true if has first element
        
        assertTrue(it.next() != null); //Should return first element
        
        assertTrue(it.hasNext()); //Return true if has second element

        assertTrue(it.next() != null); //Should return second element
        
        assertFalse(it.hasNext()); //Return false, no third element

        assertTrue(it.next() == null); //Return true, no third element          
    }
and I can't figure out a way to pass all of these tests. I have written several variants and none of them works completely, only partially, inconsistently. I just don't know how to write it.

The SimpleHashSet is declared like this:
public class SimpleHashSet<E> extends AbstractSet<E> {
    private static final int SIZE = 11;
    LinkedList<E>[] buckets = new LinkedList[SIZE];
}
I appreciate all help and guidance,
PR.
This post has been answered by YoungWinston on Jul 27 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 26 2011
Added on Jul 27 2011
13 comments
1,476 views