本帖最后由 张吉日 于 2012-9-5 13:51 编辑
- 我的问题是 Mycompare类的比较器,如果没有if判断年龄语句,就光判断名字的自然排序
- 加上if判断语句的话就在名字相同时 判断年龄的大小。
- 当TreeSet ts = new TreeSet(new MyCompare());接入比较器之后
- 里面具体是怎么实现的呢?
- 我的问题可能有点乱,希望大家帮忙解除疑惑...谢谢
- ------------------------------------------------------------
- import java.util.*;
- 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)
- {
- //return 0;
-
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student s = (Student)obj;
- //System.out.println(this.name+"....compareto....."+s.name);
- 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;
- }
- }
- class TreeSetDemo2
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyCompare());
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi02",21));
- ts.add(new Student("lisi007",20));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"..."+stu.getAge());
- }
- }
- }
- // MyCompare类的比较器*********************************
- class MyCompare implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
- int num = s1.getName().compareTo(s2.getName());
- if(num==0)
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return num;
- }
- }
复制代码 |