Collections
一、概述
Collections是针对集合操作的工具类。
二、常用方法
- public static <T extends Comparable <? super T>> void sort(List <T> list):将列表升序排序
- public static void reverse(List <T> list):反转列表中的元素
- public static void shuffle(List <T> list):使用默认的随机源排列列表
三、案例
1.需求
ArrayList存储学生对象,利用Collections对ArrayList进行排序,按照年龄从小到大排序,年龄一样大时,按照姓名的字母顺序进行排序。
2.思路
1)定义学生类
2)创建ArrayList集合对象
3)创建义学生对象
4)把学生对象添加到集合中
5)使用Collections对ArrayList进行排序
6)遍历ArrayList集合
3.代码实现
Student类:
package CollectionsStudy;
public class Student {
private String name;
private int age;
public Student() {
}
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;
}
}
Demo类:
package CollectionsStudy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Demo {
public static void main(String[] args) {
//创建ArrayList集合对象
ArrayList<Student> arrayList = new ArrayList<>();
//创建学生对象
Student s1 = new Student("qwe",12);
Student s2 = new Student("asd",13);
Student s3 = new Student("zxc",11);
Student s4 = new Student("wh",13);
//把学生对象添加到集合中去
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
//使用Collections排序
Collections.sort(arrayList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
num=(num==0?s1.getName().compareTo(s2.getName()):num);
return num;
}
});
//遍历
for (Student student : arrayList) {
System.out.println(student.getName()+","+student.getAge());
}
}
}