comparable接口,arrayList<>排序
https://blog.youkuaiyun.com/chunxiaqiudong5/article/details/52760058
1.要比较的实体类继承Comparable接口
2.重写comparaTo()方法;在该方法中可以设置计较策略,
result=this.age.compareTo(o.getAge());
result==0 表示this.age == o.getAge()
result == 1 表示 this.age > o.getAge()
result ==-1 表示this.age <o.getAge()
3.Collection.sort(sList);
package com.example.study.comparabel;
/**
* @program: demo
* @description: 测试实体类
* @author: sjk
* @create: 2018-09-13 15:23
**/
public class Student implements Comparable<Student> {
private Integer age;
private Integer score;
private String name;
public Student(Integer age, Integer score, String name) {
this.age = age;
this.score = score;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", score=" + score +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Student o) {
//o是当前传入的 strudent
//this 是下一个要比较的student
//this.age和o.age 相等 result=0
//this.age>o.age result=1
//this.age<o.age result=-1
int result =0;
result=this.age.compareTo(o.getAge());
if(result==0){
result=this.score.compareTo(o.getScore());
}
return result;
}
}
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @program: demo
* @description: 测试
* @author: sjk
* @create: 2018-09-13 15:30
**/
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class ComparableTest {
@Test
public void test1() {
List<Student> sList = new ArrayList<>();
Student s1 = new Student(18,80,"张三");
Student s2 = new Student(19,81,"张四");
Student s3 = new Student(20,83,"张五");
Student s4 = new Student(20,82,"张六");
sList.add(s2);
sList.add(s3);
sList.add(s4);
sList.add(s1);
Collections.sort(sList);
for (Student s : sList) {
System.out.println(s.toString());
}
}
}