java鎬庝箞瀹炵幇瀵硅嚜瀹氫箟绫诲瀷鎺掑簭
瑕佸疄鐜板鑷畾涔夌被鍨嬫帓搴忥紝闇€瑕佹弧瓒充袱涓潯浠讹細
-
鑷畾涔夌被鍨嬮渶瑕佸疄鐜?
Comparable
鎺ュ彛锛屽嵆瀹炵幇compareTo
鏂规硶銆傝鏂规硶瀹氫箟浜嗚嚜瀹氫箟绫诲瀷鐨勬帓搴忚鍒欍€?/p> -
浣跨敤鎺掑簭绠楁硶瀵硅嚜瀹氫箟绫诲瀷鐨勯泦鍚堣繘琛屾帓搴忋€?/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>