Search code examples
javaiteratorqueueheap

How to write a next method with an Iterator and a MaxHeapPriorityQueue in java


I need help writing this next() method in this class. I've tried several stuff, but I keep getting that I'm not returning the next value, but rather null.

The instructions for this class reads: This class should be public, non-static, and should implement java.util.Iterator. It's index instance variable should be initialized with an appropriate value. It's hasNext() method should return true if any elements in the queue have yet to be returned by its next() method. It's next() method should return queue values in the same order as in the underlying array.

Therefore I'm going to write the code that I have, but will cut it short so only the important elements that are relatable to my problem shows.

public class MaxHeapPriorityQueue<E extends Comparable<E>>
{
private E[] elementData;
private int size;

@SuppressWarnings("unchecked")
public MaxHeapPriorityQueue()
{
    elementData = (E[]) new Comparable[10];
    size = 0;
}
public Iterator<E> iterator()
{
    return new MHPQIterator();
}

and the other class takes place here, which has ties with the Iterator method.

public class MHPQIterator implements java.util.Iterator<E>
{
    private int index;

    public boolean hasNext()
    {
        if(size == 0)
        {
            return false;
        }
        else
        {
            return (index < size);
        }
    }
    public E next()
    {
        return elementData[index];
    }
}

I'm not sure if I'm elementData would work, but I don't know what else I could return with.


Solution

  • First of all, my understanding is, that your data is inside elementData and size gives the number of elements stored inside.

    iterator() gives you an iterator. Your Iterator implementation has index as a point to the current element.

    What do you plan to store inside index? I see 2 possibilities: a) it is giving you the current data location. The first element inside the array is element 0, so to be before that, I would initialize it as -1. b) It could be visual. So it is initialized as 0 first and then 1 means: first element, which would be the elementData[0]. ==> It is just an internal variable so it is completely up to you, what you want to store inside of it.

    Now let us look at your hasNext method. If the sizer is 0, then there cannot be a next element. Ok. But then you check if iterator() is null? iterator always returns a new instance of your inner iterator class. So it will always be non null! So this seems wrong.

    You have index and size. So you just have to check if the index is already pointing to the last element. So depending on the choice a/b above, you simply have to check if index+1 < size or index

    And then the next function: - It has to validate that there is another element. (=> hasNext) - you increase index - you return the element, index is pointing to (elementData[index] or elementData[index-1] (depends again on your decision what to store inside index)

    My hint is, to play around with it with paper and pen. Just write an instance of your class with e.g. 3 elements (so elementData[0], elementData[1], elementData[2] hs some value, size = 3. You create a new instance of your iterator, index is initialized and then see what must happen.

    A possible class that shows an implementation is: import java.util.Iterator;

    public class MaxHeapPriorityQueue<E extends Comparable<E>> {
        private E[] elementData;
        private int size;
    
        @SuppressWarnings("unchecked")
        public MaxHeapPriorityQueue() {
            elementData = (E[]) new Comparable[10];
            size = 0;
        }
    
        public void add(E data) {
            if (size == 10) throw new IllegalStateException("Queue full");
    
            elementData[size] = data;
            size++;
        }
    
        public Iterator<E> iterator() {
            return new MHPQIterator();
        }
    
        public class MHPQIterator implements java.util.Iterator<E>
        {
            private int index=-1;
    
            public boolean hasNext()
            {
                return (index+1)<size;
            }
    
            public E next()
            {
                index++;
                return elementData[index];
            }
        }
    
        public static void main (String[] args) {
            MaxHeapPriorityQueue<Integer> queue = new MaxHeapPriorityQueue<>();
            Iterator<Integer> iterator = queue.iterator();
    
            System.out.println("Empty queue:");
            while (iterator.hasNext())
                System.out.println(iterator.next());
    
            queue.add(1);
    
            System.out.println("Queue with 1 element (1):");
            iterator = queue.iterator();
            while (iterator.hasNext())
                System.out.println(iterator.next());
    
            queue.add(2);
            queue.add(3);
            queue.add(4);
    
            System.out.println("Queue with 4 elementa (1,2,3,4):");
            iterator = queue.iterator();
            while (iterator.hasNext())
                System.out.println(iterator.next());
        }
    }