本帖最后由 未名以律 于 2014-8-7 14:38 编辑
- import java.util.*;
- class Student implements Comparable<Student> //声明类,创建类属性
- {
- String name;
- int age;
- int score;
- Student(String name,int age,int score)//初始化属性
- {
- this.name=name;
- this.age=age;
- this.score=score;
- }
-
- public String getName()//提供姓名调用方法
- {
- return name;
- }
- public int getAge()//提供年龄调用方法
- {
- return age;
- }
- public int getScore()//提供成绩调用方法
- {
- return score;
- }
- public int compareTo(Student stu)//考虑成绩相同,所以需要比较名字
- {
- if(this.score>stu.score) return 1; //主要条件成绩比较
- else if(this.score<stu.score) return -1;
- else if(this.name.compareTo(stu.name)>0) return 1;//次要条件名字比较
- else if(this.name.compareTo(stu.name)<0)return -1;
- return 0;//如果成绩与名字都相等则为0
- }
- }
-
- public class Test10
- {
- public static void main(String[] args)
- {
- TreeSet<Student> scoreForm = new TreeSet<Student>(); // 创建TreeSet对象scoreForm
-
- scoreForm.add(new Student("zhangsan", 15, 78));// 创建5个对象装入TreeSet
- scoreForm.add(new Student("lisi", 14, 62));
- scoreForm.add(new Student("wangwu", 15, 85));
- scoreForm.add(new Student("zhaoliu", 16, 92));
- scoreForm.add(new Student("sunqi", 16, 85));
-
- Iterator<Student> iter = scoreForm.iterator();//迭代器接口
-
- while (iter.hasNext()) // // 遍历成绩
- {
- Student student = (Student) iter.next();
- System.out.println("姓名:" + student.getName() + ",年龄:"
- + student.getAge() + ",成绩:" + student.getScore());
- }
- }
- }
复制代码 |
|