Erreur: « Exception dans le thread » principal « java.lang.ClassCastException: manycard.Main Card $ ne peut pas être jeté à java.lang.Comparable »

StackOverflow https://stackoverflow.com/questions/5852719

Question

Salut à tous. Je suis en train de trier un tableau d'entiers en utilisant la méthode Array.sort, et je continue à obtenir l'erreur ci-dessus. J'ai regardé des exemples de cette méthode en cours d'utilisation, et j'utilise la même syntaxe. Parce que je suis sûr que ce sera nécessaire, voici le morceau de code que je utilise:

    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;
}
Était-ce utile?

La solution

Your Card class needs to implement Comparable<Card>. This is needed so that the Arrays.sort method can call the compareTo(Card card) method that you will implement in Card and do the sorting based on its return value.

From the documentation, compareTo does the following:

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.

Autres conseils

Card needs to implement the Comparable interface, specifically the compareTo method.

You call Arrays.sort on deck.cards that is an array of Card objects, not an array of integers. Your Card class needs to implement comparable.

In order to use Arrays.sort(Object[] o), the object you're sorting must implement the Compareable interface.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top