Java " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞瀹炵幇瀵硅嚜瀹氫箟绫诲瀷鎺掑簭

扬州沐宇科技
2023-11-08 19:32:00
Java

瑕佸疄鐜板鑷畾涔夌被鍨嬫帓搴忥紝闇€瑕佹弧瓒充袱涓潯浠讹細

  1. 鑷畾涔夌被鍨嬮渶瑕佸疄鐜?Comparable 鎺ュ彛锛屽嵆瀹炵幇 compareTo 鏂规硶銆傝鏂规硶瀹氫箟浜嗚嚜瀹氫箟绫诲瀷鐨勬帓搴忚鍒欍€?/p>

  2. 浣跨敤鎺掑簭绠楁硶瀵硅嚜瀹氫箟绫诲瀷鐨勯泦鍚堣繘琛屾帓搴忋€?/p>

浠ヤ笅鏄ず渚嬩唬鐮侊細

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Person implements Comparable<Person> {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    @Override
    public int compareTo(Person p) {
        // 鏍规嵁骞撮緞杩涜鎺掑簭
        if (this.age < p.getAge()) {
            return -1;
        } else if (this.age > p.getAge()) {
            return 1;
        } else {
            return 0;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 25));
        personList.add(new Person("Bob", 30));
        personList.add(new Person("Charlie", 20));
        
        // 浣跨敤 Collections.sort 鏂规硶瀵归泦鍚堣繘琛屾帓搴?/span>
        Collections.sort(personList);
        
        for (Person p : personList) {
            System.out.println(p.getName() + " - " + p.getAge());
        }
    }
}

浠ヤ笂浠g爜涓紝Person 绫诲疄鐜颁簡 Comparable<Person> 鎺ュ彛锛屽苟閲嶅啓浜?compareTo 鏂规硶銆傚湪 main 鏂规硶涓紝棣栧厛鍒涘缓浜嗕竴涓?Person 绫诲瀷鐨勯泦鍚?personList锛岀劧鍚庝娇鐢?Collections.sort 鏂规硶瀵硅闆嗗悎杩涜鎺掑簭銆傛渶鍚庯紝閫氳繃閬嶅巻闆嗗悎锛屾墦鍗板嚭鎺掑簭鍚庣殑缁撴灉銆?/p>

扫码添加客服微信