Java中用Comparable实现多条件排序

文章介绍了如何在Java中使用Comparable接口实现Student类的自定义排序,通过compareTo方法按照语文、数学、英语成绩及姓名排序学生对象。
摘要由CSDN通过智能技术生成

1.创建学生类

public class Student implements Comparable<Student> {
    private String name;
    private int chineseScore;
    private int mathScore;
    private int englishScore;

    public Student(String name, int chineseScore, int mathScore, int englishScore) {
        this.name = name;
        this.chineseScore = chineseScore;
        this.mathScore = mathScore;
        this.englishScore = englishScore;
    }

    // Getters
    public String getName() {
        return name;
    }

    public int getChineseScore() {
        return chineseScore;
    }

    public int getMathScore() {
        return mathScore;
    }

    public int getEnglishScore() {
        return englishScore;
    }

    // Setters
    public void setName(String name) {
        this.name = name;
    }

    public void setChineseScore(int chineseScore) {
        this.chineseScore = chineseScore;
    }

    public void setMathScore(int mathScore) {
        this.mathScore = mathScore;
    }

    public void setEnglishScore(int englishScore) {
        this.englishScore = englishScore;
    }

    @Override
    public int compareTo(Student other) {
        if (this.chineseScore != other.chineseScore) {
            return Integer.compare(other.chineseScore, this.chineseScore);
        }
        if (this.mathScore != other.mathScore) {
            return Integer.compare(other.mathScore, this.mathScore);
        }
        if (this.englishScore != other.englishScore) {
            return Integer.compare(other.englishScore, this.englishScore);
        }
        return this.name.compareTo(other.name);
    }

    @Override
    public String toString() {
        return "Student{" +
               "name='" + name + '\'' +
               ", chineseScore=" + chineseScore +
               ", mathScore=" + mathScore +
               ", englishScore=" + englishScore +
               '}';
    }
}

2.main方法测试类

import java.util.*;

public class StudentTest {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 81, 90, 100),
            new Student("Bob", 80, 90, 90),
            new Student("Cob", 80, 90, 90),
            new Student("Charlie", 80, 90, 100),
            new Student("Dave", 70, 80, 90)
        );

        Collections.sort(students);

        for (Student student : students) {
            System.out.println(student);
        }
    }
}

在Java中,Comparable接口使对象能够相互比较。该接口定义了一个compareTo方法,该方法用于指定对象排序的方式。在Student类中,我们实现了这个接口并覆盖了compareTo方法,用以定义学生对象(Student对象)之间的排序规则。

compareTo方法中,我们首先比较学生的语文成绩。如果两个学生的语文成绩不同,则按成绩降序排列(得分高的排在前)。如果它们的语文成绩相同,我们则接着比较他们的数学成绩。如果数学成绩也相同,接下来比较英语成绩。如果所有的成绩都一样,最后根据学生姓名的字母顺序升序排列。

在确定了这个比较逻辑后,我们可以很容易地对一个包含Student对象的集合进行排序。只需要调用Collections.sort()方法,并传入我们的学生列表。然后Java的排序算法将使用我们定义的compareTo方法为这些对象排序。排序的结果将使得列表根据指定的规则排列,即首先是语文成绩最高的学生,然后是数学成绩,接着是英语成绩,最后是姓名的字母顺序。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是在Java中用多种方法实现SJF算法的示例代码: 方法一:使用数组实现 ```java public class SJF { public static void main(String[] args) { // 进程列表 String[] processNames = {"P1", "P2", "P3", "P4", "P5"}; int[] runTimes = {3, 2, 1, 4, 2}; int[] arriveTimes = {0, 1, 2, 3, 4}; int n = processNames.length; // 进程数量 int[] status = new int[n]; // 进程状态,0表示未到达,1表示已到达,2表示已完成 int[] remainTimes = new int[n]; // 剩余运行时间 // 初始化 for (int i = 0; i < n; i++) { status[i] = 0; remainTimes[i] = runTimes[i]; } int currTime = 0; // 当前时间 int finishedCount = 0; // 已完成进程数量 // 运行进程 while (finishedCount < n) { int shortestJob = -1; // 最短作业的进程编号 int shortestTime = Integer.MAX_VALUE; // 最短作业的运行时间 for (int i = 0; i < n; i++) { if (status[i] == 1 && remainTimes[i] < shortestTime) { shortestJob = i; shortestTime = remainTimes[i]; } } if (shortestJob == -1) { currTime++; continue; } System.out.println("Time " + currTime + ": " + processNames[shortestJob] + " is running"); remainTimes[shortestJob]--; currTime++; if (remainTimes[shortestJob] == 0) { System.out.println("Time " + currTime + ": " + processNames[shortestJob] + " is finished"); status[shortestJob] = 2; finishedCount++; } else if (arriveTimes[shortestJob+1] <= currTime) { status[shortestJob+1] = 1; } } } } ``` 方法二:使用链表实现 ```java public class SJF { static class Process { String name; int runTime; int arriveTime; Process(String name, int runTime, int arriveTime) { this.name = name; this.runTime = runTime; this.arriveTime = arriveTime; } } static class Node { Process process; Node next; Node(Process process) { this.process = process; this.next = null; } } static class LinkedList { Node head; LinkedList() { this.head = null; } // 插入节点 void insert(Process process) { Node newNode = new Node(process); if (head == null) { head = newNode; return; } if (process.runTime < head.process.runTime) { newNode.next = head; head = newNode; return; } Node curr = head; while (curr.next != null && curr.next.process.runTime < process.runTime) { curr = curr.next; } newNode.next = curr.next; curr.next = newNode; } // 删除节点 void delete(Node node) { if (node == head) { head = head.next; return; } Node curr = head; while (curr.next != node) { curr = curr.next; } curr.next = node.next; } } public static void main(String[] args) { // 进程列表 Process[] processes = { new Process("P1", 3, 0), new Process("P2", 2, 1), new Process("P3", 1, 2), new Process("P4", 4, 3), new Process("P5", 2, 4) }; LinkedList processList = new LinkedList(); // 初始化 for (Process process : processes) { processList.insert(process); } int currTime = 0; // 当前时间 int finishedCount = 0; // 已完成进程数量 Node currNode = processList.head; // 当前进程节点 // 运行进程 while (finishedCount < processes.length) { if (currNode == null) { currTime++; continue; } System.out.println("Time " + currTime + ": " + currNode.process.name + " is running"); currNode.process.runTime--; currTime++; if (currNode.process.runTime == 0) { System.out.println("Time " + currTime + ": " + currNode.process.name + " is finished"); processList.delete(currNode); finishedCount++; } else if (currNode.next != null && currNode.next.process.arriveTime <= currTime) { Node nextNode = currNode.next; processList.delete(nextNode); processList.insert(nextNode.process); } currNode = processList.head; } } } ``` 方法三:使用优先队列实现 ```java import java.util.PriorityQueue; public class SJF { static class Process implements Comparable<Process> { String name; int runTime; int arriveTime; Process(String name, int runTime, int arriveTime) { this.name = name; this.runTime = runTime; this.arriveTime = arriveTime; } @Override public int compareTo(Process o) { return Integer.compare(runTime, o.runTime); } } public static void main(String[] args) { // 进程列表 Process[] processes = { new Process("P1", 3, 0), new Process("P2", 2, 1), new Process("P3", 1, 2), new Process("P4", 4, 3), new Process("P5", 2, 4) }; PriorityQueue<Process> processQueue = new PriorityQueue<>(); for (Process process : processes) { processQueue.offer(process); } int currTime = 0; // 当前时间 int finishedCount = 0; // 已完成进程数量 // 运行进程 while (finishedCount < processes.length) { if (processQueue.isEmpty()) { currTime++; continue; } Process currProcess = processQueue.poll(); System.out.println("Time " + currTime + ": " + currProcess.name + " is running"); currProcess.runTime--; currTime++; if (currProcess.runTime == 0) { System.out.println("Time " + currTime + ": " + currProcess.name + " is finished"); finishedCount++; } else { for (Process process : processes) { if (process.arriveTime <= currTime && !processQueue.contains(process)) { processQueue.offer(process); } } processQueue.offer(currProcess); } } } } ``` 以上三种方法都可以实现SJF算法,方法一使用数组,方法二使用链表,方法三使用优先队列。其中,使用优先队列实现最简单,但是需要重写进程类的 `compareTo` 方法。使用数组和链表实现需要手动实现进程的排序和插入操作,但是可以更灵活地控制进程的顺序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值