本帖最后由 王广亚 于 2013-9-16 17:44 编辑
不知楼主是否还记得比较器?一样的道理- <p>import java.io.*;
- import java.util.*;
- 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;
- }
- }
- class TreeSetDemo2
- {
- public static <T> void main(String[] args)
- {
- TreeSet<Student> ts = new TreeSet<Student>(new MyCompare<Object>());</p><p> ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi02",21));
- ts.add(new Student("lisi007",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi06",18));
- ts.add(new Student("lisi06",18));
- ts.add(new Student("lisi007",29));
- Iterator<Student> it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"..."+stu.getAge());
- }
- }
- }
- class MyCompare<T> implements Comparator<T>//定义比较器
- {
- 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;
- }
- }</p>
复制代码 |