- package cn.itcast.eclips;
- import java.sql.Statement;
- import java.util.*;
- public class demo1 {
- /**
- * @param args
- */
- public static void main (String[] args) {
- TreeSet ts = new TreeSet();
-
- ts.add(new Student("li",22,33));
- ts.add(new Student("zhang",21,99));
- ts.add(new Student("wang",23,20));
- ts.add(new Student("dong",25,50));
- ts.add(new Student("ka",37,60));
-
- Iterator it = ts.iterator();
- while( ((Iterator) it).hasNext())
- {
- Student stu = (Student)it.next();
- System.out.print(stu.getGrade()+"..."+stu.getAge()+"..."+stu.getGrade() );
- }
-
- }
- class Student implements Comparable
- private String name;
- private int age;
- private int grade;
- public Student(String name,int age,int grade)
- {
- this.name = name;
- this.age = age;
- this.grade = grade;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public int getGrade()
- {
- return grade;
- }
- public void setGrade(int grade)
- {
- this.grade = grade;
- }
- public int compareto(Object obj)
- {
- Student si = (Student)obj;
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生");
- Student s = (Student)obj;
- if(this.grade>s.grade)
- return 1;
- if(this.grade<s.grade)
- return -1;
- if(this.grade==s.grade)
- return this.name.compareTo(s.name);
- }
- }
复制代码 |
|