Java排序 Comparable(实现Comparable接口)

1、首先新建第一个Student类
/**
* 排序测试 通过实现Comprable的compareTo方法进行排序
*/
public class Student implements Comparable<Student>{

private String name;

private Integer age; //排序字段

private Long time; //排序字段

public Student(){}

public Student(String name, Integer age,Long time) {
this.name = name;
this.age = age;
this.time = time;
}

//此处省略了getter和setter方法

@Override
public int compareTo(Student o) {
if (this.age > o.age) {
return 1;
}
if (this.age.equals(o.age)) {
if (this.time > o.time) {
return 1;
}
if (this.time.equals(o.time)) {
return 0;
}
if (this.time < o.time) {
return -1;
}
}
if (this.age < o.age) {
return -1;
}
return 0;
}
}

2、写一个main方法测试下
package com.example.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* 排序测试 通过实现comparable接口
*/
public class SortTest {

public static void main(String[] args) {
List<Student> list1 = getList();
System.out.println("排序:升序");
Collections.sort(list1);
System.out.println(list1);

List<Student> list2 = getList();
System.out.println("排序:降序");
list2.sort(Collections.reverseOrder());
System.out.println(list2);

List<Student> list3 = getList();
System.out.println("将list反序输出");
Collections.reverse(list3);
System.out.println(list3);
}

private static List<Student> getList() {
Student s1 = new Student("学生1",1,1L);
Student s2 = new Student("学生2",3,2L);
Student s3 = new Student("学生3",2,3L);
Student s4 = new Student("学生4",2,4L);
Student s5 = new Student("学生5",5,5L);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
return list;
}
}

3、输出结果:
排序:升序
[Student{name='学生1', age=1, time=1}, Student{name='学生3', age=2, time=3}, Student{name='学生4', age=2, time=4}, Student{name='学生2', age=3, time=2}, Student{name='学生5', age=5, time=5}]
排序:降序
[Student{name='学生5', age=5, time=5}, Student{name='学生2', age=3, time=2}, Student{name='学生4', age=2, time=4}, Student{name='学生3', age=2, time=3}, Student{name='学生1', age=1, time=1}]
将list反序输出
[Student{name='学生5', age=5, time=5}, Student{name='学生4', age=2, time=4}, Student{name='学生3', age=2, time=3}, Student{name='学生2', age=3, time=2}, Student{name='学生1', age=1, time=1}]

猜你喜欢

转载自blog.csdn.net/lichuangcsdn/article/details/80842223