Search code examples
javaclasscastexceptionplaying-cards

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


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;
}

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.