简体   繁体   English

类强制转换异常和泛型(java)

[英]class cast exception and generics (java)

I am implementing my own priority queue and using a class called sportsball that uses it. 我正在实现自己的优先级队列,并使用一个使用它的名为sportsball的类。 The priority queue is based on generics and uses a Node (T object, int value) (aka Name of player and their score). 优先级队列基于泛型,并使用Node(T对象,int值)(即玩家名称及其分数)。 I am getting a class cast exception error when I try to run the program. 尝试运行程序时出现类强制转换异常错误。

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node;
    at PriorityQueue.<init>(PriorityQueue.java:35)
    at sportsball.main(sportsball.java:48) 

The lines in question are: PriorityQueue.java:35: 有问题的行是:PriorityQueue.java:35:

Node[] array = (Node[])(new Object[initialSize]);

sportsball.java:48: sportsball.java:48:

PriorityQueue<String> queue = new PriorityQueue<String>(start, step);

Thank you for your help! 谢谢您的帮助!

Note: 注意:

When I tried having line PriorityQueue.java:35: 当我尝试使用PriorityQueue.java:35行时:

Node[] array = new Node[initialSize];

the error: generic array creation pops up instead. 错误:将弹出通用数组创建。

You cannot cast an Object to a Node , so you shouldn't be able to cast an Object[] to a Node[] . 您不能将Object转换为Node ,因此您不应将Object[] Node[]转换为Node[] Just create the Node[] directly. 只需直接创建Node[]

Node[] array = new Node[initialSize];

You cannot cast object to the Node as you did 您不能像以前那样将对象投射到节点上

Node[] array = (Node[])(new Object[initialSize]);

hence the exception ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node 因此,出现了ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node which is clear that object cannot be castable to Node Type ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node ,这很明显对象无法ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node为Node Type

So you can go with this option 所以你可以选择这个选项

Node[] array = new Node[initialSize];

You cannot simply cast an Object[] to a Node[]. 您不能简单地将Object []强制转换为Node []。 This will indeed generate a ClassCastException. 这确实会生成ClassCastException。 Just create a Node[] instead ( Node[] array = new Node[initialSize]; ). 只需创建一个Node []即可( Node[] array = new Node[initialSize]; )。 Without more code than this, I cannot say anything else about it. 没有比这更多的代码,我无话可说。

Note that the message of the ClassCastException is already indicating the problem. 请注意,ClassCastException消息已经表明了问题。 [Ljava.lang.Object; refers to Object[] and similarly, [LPriorityQueue$Node; 引用Object[] ,类似地, [LPriorityQueue$Node; refers to Node[] . Node[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM