1

对于我的数据结构类,我正在尝试编写一个模拟洗车的程序,并且我想使用优先级队列为高档汽车赋予比普通汽车更高的优先级。我遇到的问题与 Java 无法将“Object”类型转换为“ArrayQueue”(一个简单的 FIFO 实现)有关。我做错了什么,我该如何解决?

public class PriorityQueue<E>
{

    private ArrayQueue<E>[] queues;
    private int highest=0;
    private int manyItems=0;


    public PriorityQueue(int h)
    {
        highest=h;
        queues = (ArrayQueue<E>[]) new Object[highest+1];   <----problem is here
    }


    public void add(E item, int priority)
    {
        queues[priority].add(item);
        manyItems++;
    }


    public boolean isEmpty( )
    {
        return (manyItems == 0);
    }


    public E remove()
    {
        E answer=null;
        int counter=0;

        do
        {
            if(!queues[highest-counter].isEmpty())
            {
                answer = queues[highest-counter].remove();
                counter=highest+1;
            }
            else
                counter++;
        }while(highest-counter>=0);

        return answer;
    }
}

编辑

谢谢你们两位对这个问题的快速回答。我按照您的建议和另一段代码解决了这个问题:

public PriorityQueue(int h)
{
    highest=h;
    queues = new ArrayQueue[highest+1];
    for(int i = 0; i <= highest; i++)
    {
        queues[i] = new ArrayQueue();
    }
}
4

2 回答 2

4

对象是对象并且(在大多数情况下)不是 ArrayQueue。所以确实演员是不可能的。

创建通用数组也是一个问题,但在您的情况下,这应该可行:

public PriorityQueue(int h)
{
    highest=h;
    queues = new ArrayQueue[highest+1];   // Gives an ignorable warning
}

编辑

您的教科书中解释的方式不正确,这本书需要一个新的修订周期;)Java中不允许建议的演员表,这就像尝试做

String forEverUseless = (String) new Object(); // this will not give an empty String
                                               // but an ouch-that-hurts-Exception

这更明显。您永远不能将一个类转换为其子类型之一(派生类)。这适用于所有类,包括数组和泛型类。

编辑 2

还有两个建议:

  1. 'add' 方法应该检查 'priority' 是否在有效的优先级范围内,否则 add 将抛出异常(如queue.add(entry, -1):)
  2. remove 方法通常有一个参数 - 您可能希望使用应从队列中删除的元素来调用它。(或者 - 如果你的意图是别的,我建议使用常见的队列操作名称poppushpeek
于 2010-05-31T06:42:20.687 回答
1

问题几乎正是您所说的-您正在制作某种类型的东西Object[]并尝试将其强制转换为ArrayQueue[],而这些类型不兼容。你应该这样做:

queues = new ArrayQueue[highest+1];
于 2010-05-31T06:41:57.663 回答