分别用Comparable和Comparator两个接口对下列四位同学的成绩做降序排序,如果成绩一样, 那在成绩排序的基础上按照年龄由小到大排序。 姓名(String
生活随笔
收集整理的這篇文章主要介紹了
分别用Comparable和Comparator两个接口对下列四位同学的成绩做降序排序,如果成绩一样, 那在成绩排序的基础上按照年龄由小到大排序。 姓名(String
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼
import java.util.*;/*3.分別用Comparable和Comparator兩個(gè)接口對(duì)下列四位同學(xué)的成績做降序排序,如果成績一樣,那在成績排序的基礎(chǔ)上按照年齡由小到大排序。姓名(String)年齡(int)分?jǐn)?shù)(float)liusan 20 90.0Flisi 22 90.0Fwangwu 20 99.0Fsunliu 22 100.0F編寫一個(gè)Student類用來實(shí)現(xiàn)Comparable<Student>接口,并在其中重寫CompareTo(Student o)方法 在主函數(shù)中使用Comparable 與 Comparetor分別對(duì)ArrayList進(jìn)行排序.*/ public class Homework3 {public static void main(String[] args) {List<Student> list = new ArrayList<>();list.add(new Student("liusan", 20, 90));list.add(new Student("lisi", 22, 90));list.add(new Student("wangwu", 20, 99));list.add(new Student("sunliu", 22, 100));Collections.sort(list, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if (o1.score == o2.score){return o1.age - o2.age;}return (int) (o2.score - o1.score);}});for (Student s : list){System.out.println(s);}} }class Student implements Comparable<Student>{String name;int age;float score;public Student(String name, int age, float score) {this.name = name;this.age = age;this.score = score;}public Student() {}@Overridepublic int compareTo(Student o) {if (this.score == o.score){return this.age - o.age;}return (int) (o.score - this.score);}@Overridepublic String toString() {return this.name + "["+ this.age +"]:" + this.score;} }總結(jié)
以上是生活随笔為你收集整理的分别用Comparable和Comparator两个接口对下列四位同学的成绩做降序排序,如果成绩一样, 那在成绩排序的基础上按照年龄由小到大排序。 姓名(String的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OJ1075: 聚餐人数统计(C语言)
- 下一篇: ZZULIOJ 1115: 数组最小值