文章目录
Collections概述和使用
概述
Collections类是针对集合操作的工具类,常用方法有:
- public static <
T
extends Comparable<T
superT
>>void sort(List<T
list>):将指定的List列表按生序排序 - public static void reverse(List<
?
>list): 反转指定列表中元素的顺序 - public static void shuffle(List<
?
>list):使用默认的随机源随机排列指定的列表
public static void main(String[] args) {
ArrayList<Integer>list=new ArrayList<>();
list.add(10);
list.add(30);
list.add(20);
list.add(80);
list.add(5);
list.add(40);
System.out.println(list);
//1. sort升序
Collections.sort(list);
System.out.println(list);
//2.reverse反转
Collections.reverse(list);
System.out.println(list);
//3.shuffle随机置换
Collections.shuffle(list);
System.out.println(list);
}
打印结果如下:
[10, 30, 20, 80, 5, 40]
[5, 10, 20, 30, 40, 80]
[80, 40, 30, 20, 10, 5]
[5, 80, 30, 20, 40, 10]
Process finished with exit code 0
使用
案例:ArrayList存储学生对象并排序,要求:按照年龄从小到大排序,年龄相同时,按照姓名和字母顺序排序
//1.定义学生类
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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 static void main(String[] args) {
//2.创建ArrayList集合对象
ArrayList<Student>list=new ArrayList<>();
//3.创建学生对象
Student student1=new Student("A",25);
Student student2=new Student("H",18);
Student student3=new Student("I",23);
Student student4=new Student("G",20);
Student student5=new Student("B",20);
//4.把学生对象添加到集合
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
//5.使用Collections对ArrayList集合排序
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
int num1=s1.getAge()-s2.getAge();
int num2=num1==0?s1.getName().compareTo(s2.getName()):num1;
return num2;
}
});
//6.遍历集合
for(Student student:list){
System.out.println(student.getName()+","+student.getAge());
}
}
打印结果如下:
H,18
B,20
G,20
I,23
A,25
Process finished with exit code 0