- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet a1=new TreeSet();
- a1.add(new Student("lisi01",20));
- a1.add(new Student("lisi03",16));
- a1.add(new Student("lisi02",24));
- a1.add(new Student("lisi02",24));
- a1.add(new Student("lisi04",19));
- a1.add(new Student("lisi05",19));
- Iterator it=a1.iterator();
- while(it.hasNext())
- {
- Student stu=(Student)it.next();
- System.out.println(stu.getName()+"......"+stu.getAge());
- }
- }
- }
- class Student implements Comparable
- {
- 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;
- }
- public int compareTo(Object obj)
- {
- 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;
- }
- }
复制代码
System.out.println(this.name+"...compareto..."+s.name);
搞不清this.name和s.name的关系,求讲解?
|
|