尝试用Java编写优先级队列,但在线程“main”中出现“异常” java.lang.ClassCastException”

发布于 2024-09-03 17:51:54 字数 1292 浏览 10 评论 0原文

对于我的数据结构课程,我正在尝试编写一个模拟洗车的程序,并且我想使用优先级队列为高档汽车提供比普通汽车更高的优先级。我遇到的问题与 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();
    }
}

For my data structure class, I am trying to write a program that simulates a car wash and I want to give fancy cars a higher priority than regular ones using a priority queue. The problem I am having has something to do with Java not being able to type cast "Object" as an "ArrayQueue" (a simple FIFO implementation). What am I doing wrong and how can I fix it?

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

EDIT

Thank you both for the quick answer to this question. I solved the problem by following your advice and one other bit of code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苄①跕圉湢 2024-09-10 17:51:54

对象就是对象并且(在大多数情况下)不是 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. 删除方法通常有一个参数 - 您可能希望使用要从队列中删除的元素来调用它。 (或者 - 如果您有其他目的,我建议使用常见的队列操作名称 poppushpeek

An Object is an Object and (in most cases) not an ArrayQueue. So indeed the cast is not possible.

Creation of generic arrays is a problem too, but in your case, this should work:

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

EDIT

The way it is explained in your textbook is incorrect, the book needs a new revision cycle ;) The suggested cast is not allowed in Java, it's like an attempt to do

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

which is more obvious. You can never cast a class to one of its subtypes (derived classes). This is true for all classes, including arrays and generic classes.

EDIT 2

Two more suggestions:

  1. The 'add' method should get a check whether 'priority' is in the valid range of priorities, otherwise add will throw an exception (like in: queue.add(entry, -1))
  2. A remove method usually has an argument - you might want to call it with the element that shall be removed from the queue. (Or - if you're intention is something else, i suggest using the common queue operation names pop, push and peek)
甜心小果奶 2024-09-10 17:51:54

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

queues = new ArrayQueue[highest+1];

The problem is almost exactly what you said -- you're making something of type Object[] and trying to cast it to ArrayQueue[], and those aren't compatible types. You should just do:

queues = new ArrayQueue[highest+1];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文