第十题
- package com.itheima;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class Test10 {
- /**
- * @param args
- * 10、声明类Student,包含3个成员变量:name、age、score,
- * 创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TreeSet<Student> treeSet=new TreeSet();
- //实例化5个student对象
- Student[] stuArr={new Student("赵", 20, 97),
- new Student("钱", 22, 84),
- new Student("孙", 21, 97),
- new Student("李", 23, 89),
- new Student("崔", 19, 99)};
- //将5个student对象增加到TreeSet对象中
- treeSet.add(stuArr[0]);
- treeSet.add(stuArr[1]);
- treeSet.add(stuArr[2]);
- treeSet.add(stuArr[3]);
- treeSet.add(stuArr[4]);
- Iterator it=treeSet.iterator();
- //获取treeSet的遍历器
- while(it.hasNext()){
- Student p = (Student)it.next();
- System.out.println("name = "+p.getName()+" || age = "+p.getAge()+" || age = "+p.getScore());
- }
- }
- static class Student implements Comparable{
- //实现Comparable 接口的compareTo(Object o)方法
- private String name;
- private int age;
- private float score;
- public Student(String n,int a,float s) {
- // TODO Auto-generated constructor stub
- name=n;
- age=a;
- score=s;
- }
- 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 float getScore() {
- return score;
- }
- public void setScore(float score) {
- this.score = score;
- }
- @Override
- public int compareTo(Object o) {
- // TODO Auto-generated method stub
- Student stu=(Student) o;
- //以下实现的是升序排列
- if(this.score>stu.score){
- return 1;
- }
- if(this.score<stu.score){
- return -1;
- }
- return 0;
- }
- }
- }
复制代码
为啥我是10个题
|