2011-05-02 31 views
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; 
} 

回答

0

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

documentationcompareTo执行以下操作:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

0

卡需要实现Comparable接口,特别是compareTo方法。

0

你叫Arrays.sortdeck.cards是卡对象的数组,而不是一个整数数组。你的卡片类需要实现可比较的。

0

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

相关问题