有时需要通过比较对象的某个值来将对象的数组进行排序,
可以通过自定义方法来实现,
但是使用comparable接口会很方便的实现不同属性的比较排序.
写一个Student类
// 泛型写什么 就是和什么比较
public class Student implements Comparable<Student>{
private String name;
private int score;
public static boolean desc; // true 降序 false 升序
// 排序方式对所有对象都是保持一致 ,使用static来保持一致
// 并且也直接使用类名调用比较简单
// 所有对象独享的,定义为静态变量
// 每个对象独享的,定义为普通变量
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int score) {
super();
this.name = name;
this.score = score;
}
public int compareTo(Student o) {
// 比较的结果返回值如下所示
// 负数 0 正数
// 负数 tihs < o
// 0 this == o
// 正数 this > o
// if (this.score < o.score) {
// return -1;
// }
// if (this.score == o.score) {
// return 0;
// }
// if (this.score > o.score) {
// return 1;
// }
// 这是一种更简便的写法
// 降序
if (Student.desc) {
return o.score - this.score;
}else {
// 升序
return this.score - o.score;
}
// 当然还有更简便的写法
return (this.score - o.score) * (Student.desc ? -1 : 1);
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
}
在创建一个Test类进行使用
public class Test {
public static void main(String[] args) {
Student s1 = new Student("张三",90);
Student s2 = new Student("李四",75);
Student s3 = new Student("王五",80);
Student s4 = new Student("马六",60);
Student s5 = new Student("田七",83);
Student s6 = new Student("赵八",71);
ArrayList<Student> al1 = new ArrayList<Student>();
al1.add(s1);
al1.add(s2);
al1.add(s3);
al1.add(s4);
al1.add(s5);
al1.add(s6);
// 使用desc来选择升降序排列
Student.desc = true;
Collections.sort(al1);
for (Student student : al1) {
System.out.println(student);
}
}
}