---
# System prepended metadata

title: Java_Cmoney_ft8107_ArrayList_Comparable
tags: [Cmoney_Java題目]

---

---
tags: Cmoney_Java題目
---
Java_Cmoney_ft8107_ArrayList_Comparable
===

![](https://i.imgur.com/wWuZOum.png)
![](https://i.imgur.com/8hXg6Tt.png)



1.需要的 function 和 class
---
1.1 class Student
---
1. 使用 Comparable interface 後面加一個比較的物件
2. compareTo() 可以回傳 3種 int 值 正、負、零
```java=
class Student implements Comparable<Student> {
    int seat;
    int score;

    Student(int seat, int score) {
        this.seat = seat;
        this.score = score;
    }

    void print() {
        System.out.println(seat + "." + score);
    }

    @Override
    public int compareTo(Student stu) {
        return this.score - stu.score;
    }
}
```


1.3 全部印出
---
```java=
public static void printAll(ArrayList<Student> students) {
        for (Student student : students) {
            student.print();
        }
    }
```


2.主程式
---
1. Collections.sort(要排的物件, 排列的順序) 默認：小到大

```java=
public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Student> students = new ArrayList<Student>();
        int number = 1;
        while (true) {
            int score = sc.nextInt();
            if (score == -1)
                break;
            students.add(new Student(number, score));
            number++;
        }
        int dir = sc.nextInt();
        if (dir == 1) {
            Collections.sort(students);
            printAll(students);
        } else {
            Collections.sort(students, Collections.reverseOrder());
            printAll(students);
        }
    }
```

3.完整程式
---
```java=
package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Student> students = new ArrayList<Student>();
        int number = 1;
        while (true) {
            int score = sc.nextInt();
            if (score == -1)
                break;
            students.add(new Student(number, score));
            number++;
        }
        int dir = sc.nextInt();
        if (dir == 1) {
            Collections.sort(students);
            printAll(students);
        } else {
            Collections.sort(students, Collections.reverseOrder());
            printAll(students);
        }
    }

    public static void printAll(ArrayList<Student> students) {
        for (Student student : students) {
            student.print();
        }
    }
}

class Student implements Comparable<Student> {
    int seat;
    int score;

    Student(int seat, int score) {
        this.seat = seat;
        this.score = score;
    }

    void print() {
        System.out.println(seat + "." + score);
    }

    @Override
    public int compareTo(Student stu) {
        return this.score - stu.score;
    }
}
```