cannot be cast to java.lang.Comparable - I get this error when not using Comparable

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

  •  23-06-2023
  •  | 
  •  

سؤال

Here is the code that the program breaks on (second line, Arrays.sort):

public void check3Kind(){       
    Arrays.sort(YahtzeeGUI.getGame().getDice()); //sorts the array so i can check for identical numbers in order

    int dice0 = YahtzeeGUI.getGame().getDice(0).getFaceValue();
    int dice1 = YahtzeeGUI.getGame().getDice(1).getFaceValue();
    int dice2 = YahtzeeGUI.getGame().getDice(2).getFaceValue();
    int dice3 = YahtzeeGUI.getGame().getDice(3).getFaceValue();
    int dice4 = YahtzeeGUI.getGame().getDice(4).getFaceValue();

    int score = + dice0 + dice1 + dice2 + dice3 + dice4;

    if ( (dice0 == dice1 && dice0 == dice2) || (dice1 == dice2 && dice1 == dice3) || (dice2 == dice3 && dice2 == dice4)){
        YahtzeeGUI.setBtnScore(11, score);
    }
}

It spits out this error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: Dice cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at Scoring.check3Kind(Scoring.java:84)
at YahtzeeGUI$RollHandler.actionPerformed(YahtzeeGUI.java:235)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I think it's something to do with sorting the array, but I'm not too sure. I've never used Comparable and don't really understand how to use it in this context

Get Game:

private static Yahtzee y = new Yahtzee();

public static Yahtzee getGame(){
    return y;
}

Get Dice:

private Dice[] dice = new Dice[5];

public Dice[] getDice(){
    return dice;
}
هل كانت مفيدة؟

المحلول

By default Arrays.sort(Object[]) will try to cast object to Comparable and use them for sorting algorithm.

In order to make sorting happen, you need the following:

public class DiceComparator implements Comparator<Dice>{
    @Override
    public int compare(final Dice o1, final Dice o2) {
        //here comes logic for comparison
        return 0;
    }
}

Arrays.sort(YahtzeeGUI.getGame().getDice(), new DiceComparator());

Another possibility to let Dice implement Comparable

public class Dice implements Comparable<Dice>{

    @Override
    public int compareTo(Dice o) {
        //here comes logic for comparison
        return 0;
    }
}

Arrays.sort(YahtzeeGUI.getGame().getDice());

نصائح أخرى

For Java to be able to sort a collection of your custom objects, it needs to know what rules to use for deciding on the order of 2 objects of that class. For example, suppose your class Dice was:

public class Dice {
    private int foo;
    private int bar;
    // getters / setters   
}

If you wanted to do Arrays.sort(diceList), and say diceList had two Dice objects dice1 (foo = 5; bar = 10), and dice2 (foo = 7; bar = 3), how will they be sorted?

So, you need to tell Java how to sort them. For this, either your class Dice needs to implement the Comparable interface, or you need to create a separate Comparator class to do the sorting based on some logic. Example for Comparable:

public class Dice implements Comparable<Dice> {
    private int foo;
    private int bar;
    // getters / setters
    public int compareTo(Dice dice) {
        if (dice == null || this.foo == dice.foo) {
            return 0;
        } else if (this.foo > dice.foo) {
            return -1;
        } else {
            return 1;
        }
    }
}

This way when you call Arrays.sort(diceList), it knows that it has to sort them based on just the foo property. In our example, since dice2.foo > dice1.foo, after sorting, the list will contain dice2 before dice1 in the list.

I encourage you to go through the javadocs for Comparable and Comparator. What you see here is just the tip of the iceberg! :)

Make these corrections in your code as follows :

int dice0 = YahtzeeGUI.getGame().getDice()[0].getFaceValue();
    int dice1 = YahtzeeGUI.getGame().getDice()[1].getFaceValue();
    int dice2 = YahtzeeGUI.getGame().getDice()[2].getFaceValue();
    int dice3 = YahtzeeGUI.getGame().getDice()[3].getFaceValue();
    int dice4 = YahtzeeGUI.getGame().getDice()[4].getFaceValue();

And, implement java.lang.Comparable interface in your Dice class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top