错误:“线程“main”中出现异常” java.lang.ClassCastException: Manycard.Main$Card 无法转换为 java.lang.Comparable”
嘿大家。我正在尝试使用 Array.sort 方法对整数数组进行排序,但不断收到上述错误。我已经查找了正在使用的此方法的示例,并且我使用相同的语法。因为我确信这是必要的,所以这是我正在使用的代码:
public class Card
{
int suit, rank;
public Card () {
this.suit = 0; this.rank = 0;
}
public Card (int suit, int rank) {
this.suit = suit; this.rank = rank;
}
}
class Deck {
Card[] cards;
public Deck (int n) {
cards = new Card[n];
}
public Deck () {
cards = new Card[52];
int index = 0;
for (int suit = 0; suit <= 3; suit++) {
for (int rank = 1; rank <= 13; rank++) {
cards[index] = new Card (suit, rank);
index++;
}
}
}
public int median (Deck deck) {
Arrays.sort(deck.cards);
return deck.cards[2].rank;
}
Hey all. I'm trying to sort an array of integers using the Array.sort method, and I keep getting the above error. I've looked up examples of this method in use, and I'm using the same syntax. Because I'm sure it will be necessary, here's the bit of code I'm using:
public class Card
{
int suit, rank;
public Card () {
this.suit = 0; this.rank = 0;
}
public Card (int suit, int rank) {
this.suit = suit; this.rank = rank;
}
}
class Deck {
Card[] cards;
public Deck (int n) {
cards = new Card[n];
}
public Deck () {
cards = new Card[52];
int index = 0;
for (int suit = 0; suit <= 3; suit++) {
for (int rank = 1; rank <= 13; rank++) {
cards[index] = new Card (suit, rank);
index++;
}
}
}
public int median (Deck deck) {
Arrays.sort(deck.cards);
return deck.cards[2].rank;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
Card
类需要实现Comparable
。这是必需的,以便Arrays.sort
方法可以调用您将在Card
中实现的compareTo(Card card)
方法并进行排序基于其返回值。来自文档 ,
compareTo
执行以下操作:Your
Card
class needs to implementComparable<Card>
. This is needed so that theArrays.sort
method can call thecompareTo(Card card)
method that you will implement inCard
and do the sorting based on its return value.From the documentation,
compareTo
does the following:Card需要实现Comparable接口,特别是compareTo方法。
Card needs to implement the Comparable interface, specifically the compareTo method.
您在
deck.cards
上调用Arrays.sort
,它是一个Card 对象数组,而不是一个整数数组。您的 Card 类需要实现可比性。You call
Arrays.sort
ondeck.cards
that is an array of Card objects, not an array of integers. Your Card class needs to implement comparable.为了使用 Arrays.sort(Object[] o),要排序的对象必须实现 Compareable 接口。
In order to use Arrays.sort(Object[] o), the object you're sorting must implement the Compareable interface.