环保设备东莞网站建设wordpress开发手册下载
泛型与集合(四)
- Collections 类
- 排序
- 查找
- 打乱元素次序
- 求极值
- 其他方法
Collections 类
Collections 类是 Java 集合框架中的一个工具类,位于 java.util 包下。它提供了一系列静态方法,用于对集合(如 List、Set、Map 等)进行各种操作,包括排序、查找、重排、求极值以及其他方法等。
排序
- 自然排序:
sort(List<T> list)
- 原理
此方法用于对实现了 Comparable 接口的元素组成的 List 集合进行自然排序。Comparable 接口定义了一个 compareTo 方法,元素通过该方法来确定自身与其他元素的大小关系。排序时,Collections.sort 方法会调用元素的 compareTo 方法进行比较和排序。
- 原理
- 自定义排序:
sort(List<T> list, Comparator<? super T> c)
- 原理
当元素没有实现 Comparable 接口,或者需要按照不同于自然顺序的规则进行排序时,可以使用该方法。通过传入一个 Comparator 接口的实现类,Comparator 接口定义了一个 compare 方法,用于比较两个元素的大小。
- 原理
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;// 定义一个实现了 Comparable 接口的类,用于自然排序演示
class Student implements Comparable<Student> {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}// 重写 compareTo 方法,按照年龄进行自然排序@Overridepublic int compareTo(Student other) {return Integer.compare(this.age, other.age);}@Overridepublic String toString() {return "Student{name='" + name + "', age=" + age + "}";}
}// 定义一个普通类,用于自定义排序演示
class Course {private String courseName;private double price;public Course(String courseName, double price) {this.courseName = courseName;this.price = price;}public String getCourseName() {return courseName;}public double getPrice() {return price;}@Overridepublic String toString() {return "Course{courseName='" + courseName + "', price=" + price + "}";}
}public class CollectionsSortDemo {public static void main(String[] args) {// 自然排序演示List<Student> studentList = new ArrayList<>();studentList.add(new Student("Alice", 22));studentList.add(new Student("Bob", 20));studentList.add(new Student("Charlie", 25));System.out.println("自然排序前的学生列表:");for (Student student : studentList) {System.out.println(student);}// 使用 Collections.sort 进行自然排序Collections.sort(studentList);System.out.println("\n自然排序后的学生列表:");for (Student student : studentList) {System.out.println(student);}// 自定义排序演示List<Course> courseList = new ArrayList<>();courseList.add(new Course("Java Programming", 200.0));courseList.add(new Course("Python Basics", 150.0));courseList.add(new Course("Data Science", 300.0));System.out.println("\n自定义排序前的课程列表:");for (Course course : courseList) {System.out.println(course);}// 自定义比较器,按照课程价格从高到低排序Comparator<Course> priceComparator = (c1, c2) -> Double.compare(c2.getPrice(), c1.getPrice());// 使用 Collections.sort 进行自定义排序Collections.sort(courseList, priceComparator);System.out.println("\n自定义排序后的课程列表:");for (Course course : courseList) {System.out.println(course);}}
}
代码解释:
- 自然排序部分:
- 定义了 Student 类并实现了 Comparable 接口,重写了 compareTo 方法,使其按照学生的年龄进行自然排序。
- 创建了一个 Student 对象的列表 studentL