集合进阶-collections

Collections概述和使用

Collections类的概述

  • 是针对集合操作的工具类

Collections类的常用方法

方法名 说明
<T extends Comparable<?super T>> void sort(List list) 将指定的列表按升序排序
void reverse(List<?> list) 反转指定列表中元素的顺序
void shuffle(List<?> list) 使用默认的随即源随机排列指定的列表

sort英文释义:排序

shuffle英文释义:洗牌

如果使用自然排序的sort方法对引用类型对象进行排序,需要在对象内实现自然排序接口并重写compareTo方法

在这里,还有一个sort方法:sort(List<?> list,comparator<? super T> c)

这个方法可以指定一个比较器对象来进行排序,例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Test {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Student s1 = new Student("XIAOBAI", 18);
Student s2 = new Student("XIAOKAI", 21);
Student s3 = new Student("XIAOXUE", 20);
list.add(s1);
list.add(s2);
list.add(s3);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num1 = o1.getAge() - o2.getAge();
int num2 = num1 == 0 ? o1.getName().compareTo(o2.getName()) : num1;
return num2;
}
});
for (Student s : list) {
System.out.println(s.getAge() + "," + s.getName());
}
}
}


集合进阶-collections
http://blog.170827.xyz/2022/08/26/集合进阶-collections/
作者
XIAOBAI
发布于
2022年8月26日
许可协议