为什么TreeSet会给出classcast异常

时间:2017-09-09 04:21:55

标签: java collections treeset

班级学生 我已经让一个班级学生接受了卷号,标准,名字和姓氏。我使用TreeSet在student中输入值。执行时我在这个程序上遇到类转换异常。是因为我输入了Treeset无法排序的异构值。

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);

}
}

具有Main()

的StudentTest类
    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());
    }
   }


    }

输出:

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 个答案:

答案 0 :(得分:0)

您需要为Comparable<>类实现Student接口。内部的树集也可以使用。

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;
        }
    }
}

答案 1 :(得分:0)

1.TreeSet是一个有序集,如果你添加到treeSet的值不能相互比较,treeSet将抛出ClassCastException。
2. Student类没有可比性,你如何期望TreeSet为你排序。也许你需要的是org.apache.commons.collections.set.ListOrderedSet。

TreeMap.put method

答案 2 :(得分:0)

根据oracle文档 https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

public TreeSet()

构造一个新的空树集,根据其元素的自然顺序排序。插入到集合中的所有元素都必须实现Comparable接口。此外,所有这些元素必须是可相互比较的:e1.compareTo(e2)不得对集合中的任何元素e1和e2抛出ClassCastException。如果用户尝试向违反此约束的集合添加元素(例如,用户尝试将字符串元素添加到其元素为整数的集合中),则add调用将抛出ClassCastException。