java实现对象比较,可以实现java.lang.Comparable或java.util.Comparator接口
方法一:将要排序的对象类实现Comparable<>接口。
首先,创建学生类,我们将根据学生成绩对学生进行排序:
/**
* 〈学生自动排序类〉
*
* @author vegetable
* @create 2018/12/2410:30
* @since 1.0.0
*/
public class Student implements Comparable<Student>{
String name;
int age;
int score;
public Student(String name, int age,int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
return this.score - o.score;
}
}
方法二:使用Comparator匿名内部类实现。
还是使用同一个例子,按成绩将学生排序:
import java.util.Comparator;
/**
* 〈学生排序器〉
*
* @author vegetable
* @create 2018/12/2410:34
* @since 1.0.0
*/
public class StudentComparable implements Comparator<Student> {
//对象的排序方式[升、降]
public static boolean sortASC=true;
// 对象的排序属性
public static boolean sortByName = false;
public static boolean sortByAge = false;
public static boolean sortByScore= false;
@Override
public int compare(Student o1, Student o2) {
int result=0;
if(sortASC){
if(sortByName){
String o1name = o1.getName();
String o2name = o2.getName();
result = o1name.compareTo(o2name);
}else if(sortByAge) {
Integer o1Age = o1.getAge();
Integer o2Age = o2.getAge();
result = o1Age.compareTo(o2Age);
}else if (sortByScore){
Integer o1Score = o1.getScore();
Integer o2Score = o2.getScore();
result = o1Score.compareTo(o2Score);
}
}else {
if(sortByName){
String o1name = o1.getName();
String o2name = o2.getName();
result = - o1name.compareTo(o2name);
}else if(sortByAge) {
Integer o1Age = o1.getAge();
Integer o2Age = o2.getAge();
result = - o1Age.compareTo(o2Age);
}else if (sortByScore){
Integer o1Score = o1.getScore();
Integer o2Score = o2.getScore();
result = - o1Score.compareTo(o2Score);
}
}
return result;
}
}
测试类
import java.util.ArrayList;
import java.util.Collections;
/**
* 〈学生排序测试类〉
*
* @author vegetable
* @create 2018/12/2410:46
* @since 1.0.0
*/
public class Test {
public static void main(String[] args){
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("刘一", 20, 89));
students.add(new Student("丁二", 26, 91));
students.add(new Student("王三", 23, 78));
students.add(new Student("周五", 21, 82));
System.out.println("排序前:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
}
// // 第一种排序方法
// Collections.sort(students);
//第二种排序方法
StudentComparable sort =new StudentComparable();
StudentComparable.sortASC = true;//降序
StudentComparable.sortByScore=true; //设置排序属性生效
Collections.sort(students,sort);
System.out.println("排序后:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
}
}
}