Java 实现对象数组排序
程序员文章站
2024-01-18 19:45:34
...
使用 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));
}
}