1.按照毕老师的教程里面说,只有一个ts.add(new Student("lisi02",22)); 时,下面的代码应该编译和运行都成功的,但是不知道为什么我的这个就是运行没有通过,运行后显示ClassCastException.- import java.util.*;
- class TreeSetTesting
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student("lisi02",22));
- Iterator it = ts.iterator();
- while (it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"......"+stu.getAge());
- }
- }
- }
- 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;
- }
- }
复制代码 2.之后继续完善这个代码,发现我的代码运行后比视频所说的多比较了一次,第一个对象自己和自己比较了,可能就是这样才会导致上面的代码运行不成功,但是为什么是这样的呢?- import java.util.*;
- class TreeSetTesting1
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi02",23));
- Iterator it = ts.iterator();
- while (it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"......"+stu.getAge());
- }
- }
- }
- class Student implements Comparable
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("not a student");
- Student s = (Student)obj;
- System.out.println(this.name+"::"+this.age+"...CompareTo..."+s.name+"::"+s.age);
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- return this.name.compareTo(s.name);
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码 |