本帖最后由 曹德君 于 2013-4-26 21:05 编辑
- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
-
- TreeSet ts = new TreeSet();
- ts.add(new Person("lisi001",10));
- ts.add(new Person("lisi002",20));
- ts.add(new Person("lisi003",30));
- ts.add(new Person("lisi004",40));
- ts.add(new Person("lisi007",40));
- ts.add(new Person("lisi002",40));
- for (Iterator it=ts.iterator();it.hasNext(); )
- {
- //Object obj =it.next();这里有类型提升。必须强转成Person才能输出名字和年龄。
- Person p = (Person)it.next();
- sop(p.getName()+"..m.."+p.getAge());
- }
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Person implements Comparable
- {
- 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;
- }
- public int compareTo(Object obj)
- {
- if (!(obj instanceof Person))
- {
- throw new RuntimeException("不是Person对象");//1疑问这里为什么要抛出RuntimeException异常?用horows抛为什么不行??
- }
- Person p=(Person)obj;
- if (this.age>p.age)
- return 1;
- if (this.age==p.age)
- //字符串本身也具备比较性String类里面的comparaTo()方法
- return this.name.compareTo(p.name);
- return -1;
- }
-
- }
复制代码 |