当前位置: 首页 > news >正文

【Java】泛型与集合篇(四)

泛型与集合(四)

  • 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 方法,按照年龄进行自然排序
    @Override
    public int compareTo(Student other) {
   
        return Integer.compare(this.age, other.age);
    }

    @Override
    public 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;
    }

    @Override
    public 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);
        }
    }
}

代码解释:

  1. 自然排序部分:
    • 定义了 Student 类并实现了 Comparable 接口,重写了 compareTo 方法,使其按照学生的年龄进行自然排序。
    • 创建了一个 Student 对象的列表 studentL

相关文章:

  • 简易的仿桌面文件夹上传(vue2)
  • AI进展不止于基准:深度解析Grok 3的局限
  • 为AI聊天工具添加一个知识系统 之109 详细设计之50 三性三量三境
  • 数据分析--数据清洗
  • C++ 设计模式-外观模式
  • openharmony中HDF驱动框架关键流程说明-观察者模式
  • Redis7——基础篇(四)
  • 安卓鸿蒙应用开发架构变迁
  • HTML之JavaScript Form表单事件
  • [生活杂项][运动教程]自由泳
  • 【拥抱AI】GPT Researcher的诞生
  • qemu-kvm源码解析-cpu虚拟化
  • 基于SpringBoot+Vue的在线电影购票系统的设计与实现
  • Linux中进程的状态2
  • 【杂谈】加油!!!!
  • 根据研究主题自动生成研究报告,Open Deep Research远程服务器云部署
  • Medians
  • vscode通过ssh连接服务器实现免密登录+删除
  • 【DeepSeek三部曲】DeepSeek-R1论文详细解读
  • Python 基础-使用dict和set
  • 婚姻登记“全国通办”首日观察:数据多跑路,群众少跑腿
  • 综艺还有怎样的新可能?挖掘小众文化领域
  • 重庆大学:对学术不端行为“零容忍”,发现一例、查处一例
  • 重庆大学通报本科生发14篇SCI论文处理结果
  • 巴基斯坦信德省卡拉奇发生爆炸
  • 视频|漫画家寂地:古老丝路上的文化与交流留下的独特印记