- package 练习;
- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class TreeSetTest
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet(new MyComparator());
- ts.add(new Person("lisi01",20));
- ts.add(new Person("lisi02",22));
- ts.add(new Person("lisi03",18));
- ts.add(new Person("lisi04",15));
- Iterator it=ts.iterator();
- while(it.hasNext())
- {
- Object obj=it.next();
- Person p=(Person)obj;
- System.out.println(p.getName()+"---"+p.getAge());
- }
- }
- }
- class MyComparator implements Comparator{//定义一个比较器
- public int compare(Object o1,Object o2)
- {
- //if(!((o1 instanceof Person)&&(o2 instanceof Person)))
-
- Person p1=(Person)o1;
- Person p2=(Person)o2;
- int num=new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
- if(num==0)
- return p1.getName().compareTo(p2.getName());
- return num;
- }
- }
复制代码 |
|