TreeSet中,毕老师的视频里只有一个元素时可以正常添加,为什么我只添加一个元素也报错呢?
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast
to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)
at TreeSetDemo.main(TreeSetDemo.java:19)
- /*
- TreeSet: 可以对Set集合中的元素进行排序.
- 需求:往TreeSet集合中存储学生,按年龄排序.
- */
- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- // ts.add("adc");
- // ts.add("aec");
- // ts.add("Bdbc");//大写字母数值较小,排在小写前面.
- // ts.add("abc");
- ts.add(new Student("lisi05",26));
- // ts.add(new Student("lisi02",21));
- // ts.add(new Student("lisi04",25));
- // ts.add(new Student("lisi03",22));
- Iterator it = ts.iterator();
- while (it.hasNext())
- {
- Student stu = (Student)it.next();
- sop(stu.getName()+"..."+stu.getAge());
- }
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Student
- {
- private String name;
- private int age;
- Student(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码
|