0

I keep getting Exception in thread "main" java.lang.ClassCastException: studentscoresapp.Student cannot be cast to java.lang.Comparable am not able to figure out why. Maybe someone can take a look and tell me where I am messing up. I have been messing with it for hours and it seems that I am making the program worse and nothing I have found online seems to work. Thanks

public class Student implements IComparable<Student>
{
    private String lastName;
    private String firstName;
    private int score;

    public Student(String lastName, String firstName, int score)
    {
        this.lastName = lastName;
        this.firstName = firstName;
        this.score = score;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the score
     */
    public int getScore() {
        return score;
    }

    /**
     * @param score the score to set
     */
    public void setScore(int score) {
    this.score = score;
    }

    @Override
    public int compareTo(Object obj)
        {
        Student i = (Student) obj;
        if (i.lastName.equals(lastName)) {
            return firstName.compareToIgnoreCase(i.firstName);
        } else {
            return lastName.compareToIgnoreCase(i.lastName);
        }
    }

}

My interface for compareTo override

public interface IComparable<E> {
    int compareTo(Object object);
}

and the student score app

public class StudentScoresApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Welcome message
        System.out.println("Welcome to the Student Scores Application.");
        System.out.println();
        int count = ConsoleValidator.getInt("Enter number of students to enter: ", 0);
        Student[] student = new Student[count];
        for (int j = 0; count > j; j++)
        {
            student[j] = getItem();
            System.out.println();
        }
        Arrays.sort(student);
        for (Student i : student)
        {
            System.out.println(i.getLastName() + " " + i.getFirstName() + ": " + i.getScore() + "\n");
        }
    }
    public static Student getItem()
    {
        String name = ConsoleValidator.getString("Student first name: ");
        String last = ConsoleValidator.getString("Student last name: ");
        int score = ConsoleValidator.getInt("Student score: ", 0);
        Student j = new Student(name,last,score);
        return j;
}

}

4
  • 2
    You need to implement Comparable, not IComparable. Commented Jul 6, 2013 at 2:58
  • 1
    When you want to use your own implementation, you need to use your own mechanism to sort. Commented Jul 6, 2013 at 2:59
  • 2
    I think your instructor has been using C# recently and forgot the name of the standard Java interface. Commented Jul 6, 2013 at 3:34
  • I think you are right he is always telling us about c# I think it's his true passion. I noticed it on another problem that something was off. Very frustrating since I tried to make it work. I now just extended Comparable and all works the way it should. Thanks for all the help to everyone. Commented Jul 6, 2013 at 3:49

4 Answers 4

8

The exception probably comes from this line.

Arrays.sort(student);

Internally Arrays.sort() will attempt to cast elements of the passed array to Comparable, this so it can call their compareTo() method. That is why you get a class cast exception.

Student must implement Comparable. Don't use your own IComparable interface, instead use java.lang.Comparable.

Sign up to request clarification or add additional context in comments.

2 Comments

part of the instructions for this exercise state: This class should implement the IComparable interface so the students can be sorted by name.
In that case have IComparable extend java.lang.Comparable, or, and this seems more likely to be what the instructor wants, implement your own sort method that takes an array of IComparable.
2

How do you want sort the students, Here's how we can sort the Student according to their scores

First,Convert Student class into List<Student<String, String, Integer>> studentList

and then use this piece of code

Collections.sort(studentList, new Comparator<Student>()  
    {
          public int compare(Student c1, Student c2)
          {
            if (c1.getScore() < c2.getScore()) 
                return -1;
            if (c1.getScore() > c2.getScore()) 
                return 1;
            return 0;
          }
    });

this will sort sort studentList list in ascending order according to the scores.

Comments

1

For the method Array.sort(), there is a description as:
'All elements in the array must implement the Comparable interface'.
You create the interface IComparable instead of Comparable.
I think it is not correct.
I change the interface to Comparable and it can work.

Any comments thanks for sharing.

Regards,
Hanks.

Comments

1

Although, you should have been using the standard Comparable interface the way you've written your own is also flawed. It tries to use generics but then gives it up while declaring the method. The correct implementation should have been

public interface IComparable<T> { // Use of T for types recommended
    int compareTo(T object); // Use the generic type for method as well
}

Using the standard java.lang.Comparable interface too, you should be using generics like

public class Student implements Comparable<Student> {
  // ...
  public int compareTo(Student obj) { // No need for casting now
    if (obj.lastName.equals(lastName)) {
        return firstName.compareToIgnoreCase(obj.firstName);
    } else {
        return lastName.compareToIgnoreCase(obj.lastName);
    }
  }
}

1 Comment

it is part of the requirement for me to use IComparable interface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.