Java学习之TreeSet的反序

来源:互联网 发布:else if语句怎么用java 编辑:程序博客网 时间:2024/06/10 01:31

第一次代码修改

创建了一个学生类,同时在实现Comparable接口后,重写了其中的compareto方法,使总成绩可以由高到低排序

package com.edu.homework;public class Student implements Comparable<Student>{//使用自然排序实现comparable接口并重写其中额比较方法private String name;private int chinese;private int math;private int english;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getChinese() {return chinese;}public void setChinese(int chinese) {this.chinese = chinese;}public int getMath() {return math;}public void setMath(int math) {this.math = math;}public int getEnglish() {return english;}public void setEnglish(int english) {this.english = english;}public Student(String name, int chinese, int math, int english) {super();this.name = name;this.chinese = chinese;this.math = math;this.english = english;}public Student() {super();// TODO Auto-generated constructor stub}public int getAllscores(){return chinese+math+english;}//从重写compareto方法@Overridepublic int compareTo(Student s) {int num = s.getAllscores()-this.getAllscores();//总成绩由大到小排序int num2 = num==0?this.name.compareTo(s.name):num;//如果总成绩一样,那么再按照名字自然排序return num2;}}

集合使用treeset集合这样可以指定排序方式

package com.edu.homework;import java.util.Scanner;import java.util.TreeSet;/** * 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台  * */public class Demo5 {public static void main(String[] args) {//创建treeset集合TreeSet<Student> set= new TreeSet<Student>();for (int i = 0; i < 3; i++) {Scanner scanner = new Scanner(System.in);System.out.println("请输入第"+(i+1)+"学生姓名:");String name = scanner.nextLine();System.out.println("请输入学生语文成绩:");int chinese = scanner.nextInt();System.out.println("请输入学生数学成绩:");int math = scanner.nextInt();System.out.println("请输入学生英语成绩:");int english = scanner.nextInt();//创建有参学生对象并加入数据Student s = new Student(name,chinese,math,english);//把学生对象添加到set集合中set.add(s);}//遍历set集合for (Student s : set) {//取出学生总成绩和名字System.out.println(s.getAllscores()+"  "+s.getName());}}}



0 0
原创粉丝点击