- import java.util.*;
- /*
- TreeSet排序的第二种方式:
- 当元素自身不具备比较性时,或者具备的比较性不是所需要的
- 这时就需要让集合自身具备比较性
- 在集合初始化时,就有了比较方式
- 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数
- */
- class TreeSetDemo2
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyCompare()); //将比较器作为参数传递给集合
- ts.add(new Student("lisi02",22)); //添加
- ts.add(new Student("lisi03",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi01",17));
- Iterator it = ts.iterator(); //迭代器
- while(it.hasNext()){
- Student s = (Student)it.next(); //强转
- System.out.println(s.getName()+"---"+s.getAge());
- }
- }
- }
- class Student implements Comparable //该接口强制让学生具备比较性
- {
- 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;
- }
- public int compareTo(Object obj){
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student s = (Student)obj;
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
- else
- return -1;
- }
- }
- class MyCompare implements Comparator //自定义比较器
- {
- public int compare(Object o1,Object o2){
- // Object obj = new Object();
- // if(!(obj instanceof Student))
- // throw new RuntimeException("不是学生对象");
- Student s1 = (Student)o1;
- Student s2 = (Student)o1;
- return s1.getName().compareTo(s2.getName());
- }
- }
复制代码 我是看着视频打的 但打印结果只打印了lisi02---22
后面的打印不出来
我在比较器里用if判断了下
Exception in thread "main" java.lang.RuntimeException: 不是学生对象
at MyCompare.compare(TreeSetDemo2.java:60)
at java.util.TreeMap.compare(TreeMap.java:1291)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at TreeSetDemo2.main(TreeSetDemo2.java:14)
跟我说不是学生对象
哪位大神能帮忙解答下
|
|