请注意,我只有一个学期的时间。问了类似的问题后才被重定向到here ,老实说,我无法理解其中的大部分内容,这并不是一个巨大的帮助。
我让我的代码更加完整地了解正在发生的事情(我将所有内容合并到一个主方法中。我认为这应该有一点帮助。
无论如何,我收到此错误
Exception in thread "main" java.lang.ClassCastException: lab13d.Card cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
at lab13d.Lab13d.main(Lab13d.java:53)
Java Result: 1
并且无法弄清楚它的情况。我以前从未使用过队列,所以这对我来说真的很新。
这是我的代码:
public static void main(String[] args)
{
int players = 2;
Card[] pile;
int MAX_CARDS = 52;
int MAX_SUITS = 4;
int MAX_RANKS = 14;
pile = new Card[MAX_CARDS];
int index = 0;
for(int suit = 1; suit <= MAX_SUITS; suit++){
for(int rank = 2; rank <= MAX_RANKS; rank++, index++ ){
Card c = new Card(suit, rank);
pile[index] = c;
}
}
PriorityQueue<Card>[] hand = new PriorityQueue[players + 1];
for(int i = 0; i < players + 1; i++){
hand[i] = new PriorityQueue();
}
for(int i = 0; i < players; i++){
for(int j = i; j < pile.length; j+= players){
hand[i].add(pile[j]);
}
}
int leftOverCards = pile.length - (pile.length % players);
for(int i = leftOverCards; i < pile.length; i++){
hand[players].add(pile[i]);
}
System.out.printf("%s", hand[0]);
}
最佳答案
我假设以下行抛出 ClassCastException:
hand[i].add(pile[j]);
您正在尝试将 Card 实例添加到 PriorityQueue 中,显然您的 Card 无法转换为可比较的。您需要转到 Card.java 文件并使该类实现 Comparable 接口(interface):
public class Card implements Comparable<Card>{
...
...
...
您还需要实现compareTo方法,我假设您的卡片将按它们的值进行比较,并且Card对象具有范围从2(二)到13(一张A)的int属性值。如果值相等,我们可以进行比较 - 我将把这部分留给你自己:
@Override
public int compareTo(Card o) {
int comparisonOutcome = ((Integer)o.getValue()).compareTo((Integer)this.getValue());
if(comparisonOutcome == 1 || comparisonOutcome == -1){
return comparisonOutcome;
else{
// here values are equal, we can compare by card suit
// return -1, 1 or 0
}
希望对您有所帮助。
关于java - PriorityQueue.siftUp可比较吗?我在这里做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418634/