首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Comparable 介面實作自定義排序:舉重比賽排名範例

     編輯:Java 相關知識

情境說明

某舉重比賽排名規則:

  1. 總舉起重量大者排名較前(降序)。
  2. 總重量相同時,體重較輕者排名較前(升序)。

需從資料檔案讀取選手資訊(編號、總重量、體重),依規則排序後輸出編號。本文示範如何透過實作 Comparable<T> 介面完成自定義排序邏輯。

資料檔案格式

<p> <no>1</no> <lw>140</lw> <bw>54</bw> </p>
<p> <no>2</no> <lw>155</lw> <bw>53</bw> </p>
<p> <no>3</no> <lw>140</lw> <bw>42</bw> </p>
<p> <no>4</no> <lw>140</lw> <bw>55</bw> </p>
<p> <no>5</no> <lw>130</lw> <bw>46</bw> </p>

實體類別設計

class Athlete implements Comparable<Athlete> {
    private int id;
    private int totalWeight; // 總舉起重量
    private int bodyWeight;  // 體重

    public Athlete(int id, int totalWeight, int bodyWeight) {
        this.id = id;
        this.totalWeight = totalWeight;
        this.bodyWeight = bodyWeight;
    }

    @Override
    public int compareTo(Athlete other) {
        // 規則1:總重量降序(大者在前)
        if (this.totalWeight != other.totalWeight) {
            return Integer.compare(other.totalWeight, this.totalWeight);
        }
        // 規則2:體重升序(輕者在前)
        return Integer.compare(this.bodyWeight, other.bodyWeight);
    }

    // Getter 方法
    public int getId() { return id; }
    public int getTotalWeight() { return totalWeight; }
    public int getBodyWeight() { return bodyWeight; }
}

檔案解析與排序主程式

public class WeightliftingRanking {
    public static void main(String[] args) {
        List<Athlete> athletes = new ArrayList<>();
        String filePath = "data4.txt"; // 檔案路徑

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 簡易解析:假設每 5 行一組資料,第 2、3、4 行分別為 no、lw、bw
            // 實務建議使用 XML/JSON 解析器
            while ((line = br.readLine()) != null) {
                if (line.contains("<no>")) {
                    int id = extractValue(line, "no");
                    int totalWeight = extractValue(br.readLine(), "lw");
                    int bodyWeight = extractValue(br.readLine(), "bw");
                    athletes.add(new Athlete(id, totalWeight, bodyWeight));
                    br.readLine(); // 讀掉 </p>
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 排序
        athletes.sort(null); // 使用 Comparable 自然順序

        // 輸出結果
        for (Athlete a : athletes) {
            System.out.printf("%d. 總重量:%d 體重:%d%n", a.getId(), a.getTotalWeight(), a.getBodyWeight());
        }
    }

    // 簡易標籤值提取輔助方法
    private static int extractValue(String line, String tag) {
        String pattern = "<" + tag + ">(\\d+)</" + tag + ">";
        return Integer.parseInt(line.replaceAll(".*" + pattern + ".*", "$1"));
    }
}

執行結果說明

依規則排序後順序為:

  1. 編號 2(總重量 155,體重 53)
  2. 編號 3(總重量 140,體重 42)
  3. 編號 1(總重量 140,體重 54)
  4. 編號 4(總重量 140,體重 55)
  5. 編號 5(總重量 130,體重 46)

關鍵點總結

  • compareTo 回傳負數表示 this 排在前,正數表示 other 排在前,零視為相等。
  • 善用 Integer.compare() 避免減法溢位風險,程式碼更清晰。
  • 若排序規則多變,可改用 Comparator 策略模式,將排序邏輯外部化。
  • 實務專案中資料解析建議使用成熟的 XML (DOM/SAX/StAX) 或 JSON 庫,而非字串處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved