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)
You need to implement the
Comparable<>
interface for theStudent
class. Tree set internally make use of comparable as well.