Java 實現物件陣列排序
阿新 • • 發佈:2020-12-09
技術標籤:Java演算法及JDK原始碼探究日常小知識隨筆java
使用 Arrays.sort() 對物件陣列排序
注意:
使用此方法時, 必須實現 Comparable 介面
package com.cwq.beyond;
import java.text.SimpleDateFormat;
import java.util.Arrays;
class Person implements Comparable<Person>{
private String name;
private int age;
@Override
public String toString () {
return "Person [name=" + name + ", age=" + age + "]";
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
if (this.age > o.age) {
return 1;
}else if (this.age < o. age) {
return -1;
}else {
return 0;
}
}
}
public class TestDemo {
public static void main(String[] args) throws Exception {
Person p[] = new Person[] {
new Person("張三", 20) ,
new Person("張四", 18) ,
new Person("王五", 19) ,
};
Arrays.sort(p) ;
System.out.println(Arrays.toString(p));
}
}