Error: “Exception in thread ”main“ java.lang.ClassCastException: manycard.Main$Card cannot be cast to java.lang.Comparable”

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

Pergunta

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;
}
Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top