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.