import java.util.*;
public class TestCollection01 {
public static  void main(String[] args) {
Collection  c = new TreeSet<Stu>();
Stu s1 = new Stu("小红", 20);
Stu s2 = new Stu("小明", 21);
c.add(s1);
c.add(s2);
for(Iterator<Stu> it = c.iterator();it.hasNext();) {
Stu s = it.next();
System.out.println(s.toString()); 
}
}
}
class Stu {
private String name;
private int age;

public Stu(String name,int age) {
this.name = name;
this.age = age;
}
public int hashCode() {
return 1;
}
public String toString() {
return "姓名:" + name +"年龄" + age;
}
}
Exception in thread "main" java.lang.ClassCastException: com.test02.Stu 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.test02.TestCollection01.main(TestCollection01.java:8)这个怎么错了,我把TreeSet换成HashSet就不错,arraylist和linkedlist也不错

解决方案 »

  1.   

    因为TreeSet的实现是棵红黑树,遍历TreeSet会得到一个有序的序列,但你的Stu没有实现Comparable接口,它不知道如何比较两个Stu对象,所以出错。可以实现Comparable接口,实现里面的compareTo方法。因为HashSet、ArrayList、LinkedList中的元素没有比较的需求,所以没错。
      

  2.   

    这题也不懂  用了楼上的建议 添加如下代码  就可以输出了    @Override
        public int compareTo(Object t) {
            Stu s = (Stu)t ;
             if(this.age > s.age){
                return 1 ;
            }else if(this.age<s.age){
                return -1;
            } 
            return 0 ;
        }
      

  3.   

    2楼正解,你需要自己对Stu 实现Comparable接口  以告诉TreeMap你的比较策略。他会在put的时候自动调用compareTo方法进行比较排序。
      

  4.   

    因为TreeSet的实现是棵红黑树,遍历TreeSet会得到一个有序的序列,但你的Stu没有实现Comparable接口,它不知道如何比较两个Stu对象,所以出错。可以实现Comparable接口,实现里面的compareTo方法。因为HashSet、ArrayList、LinkedList中的元素没有比较的需求,所以没错。
      

  5.   


    import java.util.Collection;
    import java.util.Iterator;
    import java.util.TreeSet;
    public class TestCollection01 {
        public static  void main(String[] args) {
            Collection  c = new TreeSet<Stu>();
            Stu s1 = new Stu("小红", 20);
            Stu s2 = new Stu("小明", 21);
            c.add(s1);
            c.add(s2);
            for(Iterator<Stu> it = c.iterator();it.hasNext();) {
                Stu s = it.next();
                System.out.println(s.toString()); 
            }
        }
    }
    class Stu implements Comparable{
        private String name;
        private int age;
        
        public Stu(String name,int age) {
            this.name = name;
            this.age = age;
        }
        public int hashCode() {
            return 1;
        }
        public String toString() {
            return "姓名:" + name +"年龄" + age;
        }
    @Override
    public int compareTo(Object o) {
    // TODO Auto-generated method stub
    return 0;
    }
    }
      

  6.   

    class Stu implements Comparable
      

  7.   

    不想实现Comparable接口,可以在实例化TreeSet时传入一个Comparator<Stu>