注意Arrays的sort方法和 Collections的sort方法的区别:
- Arrays是对数组的排序
- Collections是对列表的排序
- 二者在对类进行排序的时候要去实现它的比较方法
可比较下面一题和:贪心和类的排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<>();
al.add(new Student("dsd", 121));
al.add(new Student("dsfd", 322));
al.add(new Student("dsdff", 3));
al.add(new Student("dfsd", 13221));
//迭代器
Iterator<Student> it = al.iterator();
while(it.hasNext()) {
Student t = it.next();
System.out.print(t.name + " ");
System.out.println(t.score);
}
System.out.println("排序后:");
Collections.sort(al);
int n = al.size();
for(int i = 0; i < n; i ++) {
System.out.print(al.get(i).name + " ");
System.out.println(al.get(i).score);
}
}
}
class Student implements Comparable<Student>{
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student arg0) {
return arg0.score - this.score;
}
}
运行结果:
dsd 121
dsfd 322
dsdff 3
dfsd 13221
排序后:
dfsd 13221
dsfd 322
dsd 121
dsdff 3