0

大家好。我正在尝试使用 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;
}
4

4 回答 4

0

Card 需要实现 Comparable 接口,具体是 compareTo 方法。

于 2011-05-02T01:26:57.403 回答
0

你的Card班级需要实现Comparable<Card>. 这是必需的,以便该Arrays.sort方法可以调用compareTo(Card card)您将在其中实现的方法Card并根据其返回值进行排序。

文档中,compareTo执行以下操作:

将此对象与指定对象进行比较以进行排序。返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。

于 2011-05-02T01:27:11.573 回答
0

您调用Arrays.sortdeck.cards是 Card 对象数组,而不是整数数组。您的 Card 类需要实现可比较的。

于 2011-05-02T01:28:12.943 回答
0

为了使用 Arrays.sort(Object[] o),您要排序的对象必须实现 Compareable 接口。

于 2011-05-02T01:29:53.180 回答