1

I have a problem with my Array.sort() function. I have an array of dices with a value. I want to organize them in function of her value so I tried Array.sort() with a modification of ma class (compareTo method)

My class:

package fr.Proj.main;
import java.util.Random;


public class Dices {
private int m_value;

//Default constructor
public Dices()
{
    m_value=0;
}

public Dices(int pValue)
{
    m_value=pValue;
}

public void setDices(int pValue)
{
    m_value=pValue;
}

public int getDices()
{
    return m_value;
}

public int compareTo(Dices compareDice) {

    int compareQuantity = ((Dices) compareDice).getDices();

    //ascending order
    return m_value - compareQuantity;

}
}

Main:

         public static void main(String[] args) {
    Dices die1 = new Dices(1+rand.nextInt( 6 ));
    Dices die2 = new Dices(1+rand.nextInt( 6 ));
    Dices die3 = new Dices(1+rand.nextInt( 6 ));
    Dices die4 = new Dices(1+rand.nextInt( 6 ));
    Dices die5 = new Dices(1+rand.nextInt( 6 ));

    Dices[] tab= new Dices[5];
    tab[0]=die1;
    tab[1]=die2;
    tab[2]=die3;
    tab[3]=die4;
    tab[4]=die5;

    Arrays.sort(tab);

    System.out.println("Your dices are:");

    for (int i=0; i<tab.length; i++)
    {
        System.out.print(tab[i].getDices() + " ");
    }
}

My error:

Exception in thread "main" java.lang.ClassCastException: class fr.Proj.main.Dices cannot be cast to class java.lang.Comparable (fr.Proj.main.Dices is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.base/java.util.Arrays.sort(Arrays.java:1249)
at fr.Proj.main.Main.main(Main.java:32)

So I thank that my problem is that compareTo() method on my Dices class is not detected Thank you

Michael Ta
  • 23
  • 3

0 Answers0