TreeSet在add对象时报ClassCastException错误

TreeSet实现了SortedSet接口,可以对集合中的对象进行排序,但是在使用TreeSet时要注意一点,那就是要给TreeSet传递一个比较器,也就是指定比较规则,否则的话,它就不知道谁大谁小,也就不能排序了。此时它会报一个ClassCastException的异常。

jdk1.6文档里add方法关于这个异常是这样描述的:
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set
翻译:ClassCastException - 如果指定的对象不能与当前在此集合中的元素进行比较

public class TreeSetTest
{
    public static void main(String[] args)
    {
        MyComparator comparator = new MyComparator(); 

    //  TreeSet<Student> set = new TreeSet<Student>(comparator);
    //  错误的代码,少了比较器,运行则报下面的异常。
        TreeSet<Student> set = new TreeSet<Student>();

        Student s1 = new Student(50);
        Student s2 = new Student(70);
        Student s3 = new Student(40);

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

        System.out.println(set);
    }

}

class Student 
{
    int score;

    public Student(int score)
    {
        this.score = score;
    }
    @Override
    public String toString()
    {
        // TODO Auto-generated method stub

        return String.valueOf(this.score);
    }

}
class MyComparator implements Comparator<Student>
{

    @Override
    //按分数高低比较,int为返回负数、零、整数,这里我写的不咋好,但意思一样
    public int compare(Student o1, Student o2)
    {
        // TODO Auto-generated method stub
        int result = 0;
        if(o1.score > o2.score)
        {
            result = 1;
        }else
        {
            result = -1;
        }

        return result;
    }

}

错误的运行结果:

Exception in thread "main" java.lang.ClassCastException: com.shengsiyuan2.Student cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(TreeMap.java:1294)
    at java.util.TreeMap.put(TreeMap.java:538)
    at java.util.TreeSet.add(TreeSet.java:255)
    at com.shengsiyuan2.TreeSetTest.main(TreeSetTest.java:17)

解决办法:
把 TreeSet set = new TreeSet(); 改成:TreeSet set = new TreeSet(comparator);即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值