本文介绍了如何查找Java中的HeapQueue是否包含值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写方法时遇到了麻烦,无法确定MaxHeapPriorityQueue是否包含值.

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

读取的指令:如果在队列中找到给定值,则contains(E)方法应返回true.它应该使用其私有帮助器方法来递归搜索队列.

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);
    }
 }
}

推荐答案

我不知道为什么会有这样的麻烦,但这对我有用.我不得不使用大小而不是elementData.length.

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);
    }
}

这篇关于如何查找Java中的HeapQueue是否包含值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:42