- package com.itheima;
- import java.io.BufferedWriter;
- /**
- * 10、声明类Student,包含3个成员变量:name、age、score,
- * 创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)。
- */
- import java.util.*;
- import java.io.*;
- public class Test10
- {
- public static void main(String[] args)
- { //指定反相比较器,获取学生集合。
- Set<Student1> ts = StudentTool.getStudents(Collections.reverseOrder());
- //将排序好的学生打印到控制台。
- StudentTool.printStu(ts);
- /* int s=0;
- s++;
- System.out.println(s);定义一个局部变量s,打印,为什么这段代码不运行?而主函数其他语句正常执行,单单是这段代码不运行,
- 注:程序是我之前写的,后来练习用eclipse调试变量加了这段代码,发现问题。*/
- }
-
- }
- //描述学生
- class Student1 implements Comparable<Student1>//因为需要对学生对象进行比较。所以实现Comparable接口
- {
- private String name ;
- private int age ;
- private double score ;
- Student1(String name,int age,double score)
- {
- this.name=name;
- this.age=age;
- this.score=score;
- }
- public int compareTo(Student1 s)
- {
- int num = new Double(this.score).compareTo(new Double(s.score));//因为score是double型。需要强转
- if(num==0)
- return this.name.compareTo(s.name);//当score相同时,进一步比较姓名
- return num;
- }
- public int hashCode()//因为有可能把学生装到hashset中,所以要覆盖hashcode和equals方法
- {
- return name.hashCode()+(int)score*100;
- }
-
- public boolean equals(Object obj)
-
- {
- if(!(obj instanceof Student1))
- throw new ClassCastException("类型不匹配");
- Student1 s = (Student1)obj;
- return this.name.equals(s.name) && this.score==s.score;
- }
- public void setName(String name)
- {
- this.name =name;
- }
- public String getName()
- {
- return name;
- }
- public void setAge(int age)
- {
- this.age =age;
- }
- public int getAge()
- {
- return age;
- }
- public void setScore(double score)
- {
- this.score =score;
- }
- public double getScore()
- {
- return score;
- }
-
- public String toString()//覆盖tostring方法。便于观看
- {
- return name+"......."+score;
-
- }
- }
- class StudentTool//定义工具类
- {
- public static Set<Student1> getStudents(Comparator<Student1> cmp)//定义获取学生集合的方法
- {
- TreeSet<Student1> ts=null;
- if (cmp==null)//如果指定比较器为空。则按照自然排序
- ts = new TreeSet<Student1>();
- else
- ts = new TreeSet<Student1>(cmp);
- ts.add(new Student1("zhangfei",50,80));
- ts.add(new Student1("zhaoyun",33,99));
- ts.add(new Student1("guanyu",55,9999));
- ts.add(new Student1("liubei",23,60));
- ts.add(new Student1("liubei",23,60));
- return ts;
- }
- public static void printStu(Set<Student1> ts)//打印排序好的学生
- {
- BufferedWriter bw = null;
- try //io流的基本异常处理方式
- {
- bw = new BufferedWriter(new OutputStreamWriter(System.out));//利用转换流将内存数据输出至控制台
- for(Student1 stu : ts)//高级for循环。遍历集合
- {
- bw.write(stu.toString());
- bw.newLine();
- bw.flush();
- }
- }
- catch(IOException e)
- {
- throw new RuntimeException("打印失败");
- }
-
- finally//关闭流资源
- {
- try
- {
- if(bw!=null)
- bw.close();
- }
- catch(IOException ioe)
- {
- System.out.println("关闭流失败");
- }
-
-
-
- }
- }
- }
复制代码 |
|