Why is TreeSet giving classcast exception

1k Views Asked by At

class student I have made a class student that accepts roll number, standard, firstname and last name. I use TreeSet to enter the values in student. I am getting class cast exception on this program when executed. Is it because i am entering heterogeneus values that the Treeset cannot sort.

public class Student {

private int rollno;
private int std;
private String firstname;
private String lastname;


//getters , setters, constructors, toString

@Override
public int hashCode(){

     return Objects.hash(rollno, std, firstname,lastname);

}
}

class StudentTest that has Main()

    public class StudentTreeSet {

    public static void main(String[]args){

    Set<Student> students = new TreeSet<Student>();

    Student s1 = new Student(1,2,"Shelly","Bhargav");
    Student s2 = new Student(1,2,"Shelly","Bhargav");
    Student s3 = new Student(3,2,"Shelly","Bhargav");

    students.add(s1);
    students.add(s2);
    students.add(s3);

    students.add(s1);
    students.add(s2);
    students.add(s3);

    System.out.println();
    System.out.println();
    int studentsize2 = students.size();
    System.out.println("Again Students size ="+ studentsize2);

    for(Student student : students){
        System.out.println(student);
        System.out.println("student hashcode="+student.hashCode());
    }
   }


    }

output :

Exception in thread "main" java.lang.ClassCastException: com.techlabs.studenthashset.Student cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.techlabs.TreeSet.StudentTreeSet.main(StudentTreeSet.java:18)
3

There are 3 best solutions below

3
On

You need to implement the Comparable<> interface for the Student class. Tree set internally make use of comparable as well.

public class Student implements Comparable<Student> {    
    private int rollno;
    private int std;
    private String firstname;
    private String lastname;

    @Override
    public int compareTo(Student o) {
        if (this.rollno > o.rollno) {
            return 1;
        } else if (this.rollno == o.rollno) {
            return 0;
        } else {
            return -1;
        }
    }
}
0
On

1.TreeSet is a sorted set,if the value you add to the treeSet can't be compared to each other,treeSet will throw ClassCastException.
2. The Student class is not comparable,how do you expect the TreeSet sorted for you.Maybe what you need is org.apache.commons.collections.set.ListOrderedSet.

TreeMap.put method

0
On

As per the oracle document https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

public TreeSet()

Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException.