Search code examples
javarecursionqueueheappriority-queue

How to find if a HeapQueue contains a value in Java?


I am having trouble writing a method with finding if a MaxHeapPriorityQueue contains a value.

The instructions read: The contains(E) method should return true if the given value is found in the queue. It should use its private helper method to search the queue recursively.

Here is what I have so far

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 boolean contains(Object value)
{
     return contains(value, 0);
}
private boolean contains(Object value, int index)
 {
     if(elementData[index] != null && elementData[index] == value)
    {
        return true;
    }
    else
    {
        return contains(value, ++index);
    }
 }
}

Solution

  • I don't know why I had such trouble with this, but here is what worked for me. I had to use size instead of elementData.length.

    public boolean contains(Object value)
    {
        return contains(value, 0);
    }
    private boolean contains(Object value, int index)
    {
        if (index > size)
        {
            return false;
        }
        else if(elementData[index] == value && elementData[index] != null)
        {
            return true;
        }
        else
        {
            return contains(value, ++index);
        }
    }