Collections类仅由静态方法组成,是针对集合进行操作的工具类
//根据元素的natural ordering对集合排序
public static<T extends Comparable<? super T>> void sort(List<T> list)
//根据指定的比较器, 进行排序
public static<T> void sort(List<T> list, Comparator<? super T> c)
public static void reverse(List<?> list)//反转指定集合中元素的顺序
public static void shuffle(List<?> list)//使用默认的随机源,随机排列指定的集合
ArrayList<Student> array = new ArrayList<>();
Student s1 = new Student("linqingxia",30);
Student s2 = new Student("zhangmanyu",35);
Student s3 = new Student("wangzuxian",33);
Student s4 = new Student("liuyan",33);
array.add(s1);array.add(s2);array.add(s3);array.add(s4);
Collections.sort(array, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getScore() - o2.getScore();
int num2 = num==0? o1.getName().compareTo(o2.getName()) : num;
return num2;
}
});
for(Student e : array){System.out.println(e.getName() + "," + e.getScore());}
自然排序,被排序的类需要实现Comparable接口
比较器排序,不需要修改被排序的类,传参的时候传一个Comparator对象
Collections.sort()
Arrays.sort()
public static void main(String[] args) {
Node node1 = new Node(3);Node node2 = new Node(7);Node node3 = new Node(1);
Node[] nodes = {node1,node2,node3};
System.out.println(Arrays.toString(nodes));//371
Arrays.sort(nodes);//Node类必须实现Comparable接口,不然会报错
System.out.println(Arrays.toString(nodes));//137
}
static class Node implements Comparable<Node>{
int val;public Node(int val){this.val = val;}
@Override
public int compareTo(Node o) { return this.val - o.val;}
@Override
public String toString() { return this.val + ""; }
}