- import java.util.*;
- class TreeSetDemo
- {public static void main(String[] args)
- {TreeSet ts=new TreeSet();
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi007",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi08",19));
- ts.add(new Student("lisi007",20));
- // ts.add(new Student("lisi01",40));
-
-
- Iterator it=ts.iterator();
- while(it.hasNext())
- {Student stu=(Student)it.next();
- sop(stu.getName()+".."+stu.getAge());
- }
- }
- public static void sop(Object obj)
- {System.out.println(obj);
- }
- }
- 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)[color=Red]/*调用String方法的compareTo方法,
- int compareTo(String anotherString),按字典顺序比较两个字符串,返回值是
- int,根据返回值的正负来判断哪个大哪个小
- */
- {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;}
- }
- 希望能帮到楼主
复制代码 |