对象数组的排序需要类实现Compareable接口。
Compareable接口中的compareTo方法返回一个整型数值,用来表示两个对象的大小或相等状态。
运行结果:
ID:aaa NAME:222
ID:bbb NAME:111
ID:bbb NAME:222
Compareable接口中的compareTo方法返回一个整型数值,用来表示两个对象的大小或相等状态。
public class Person implements Comparable<Person> {
private String id;
private String name;
@Override
public String toString() {
return "ID:" + id + " NAME:" + name;
}
public int compareTo(Person o) {
int compareId = this.id.compareToIgnoreCase(o.id);
if (0 != compareId)
return compareId;
int compareName = this.name.compareToIgnoreCase(o.name);
if (0 != compareName)
return compareName;
return 0;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
Person[] p = new Person[3];
p[0] = new Person();
p[0].setId("bbb");
p[0].setName("222");
p[1] = new Person();
p[1].setId("ccc");
p[1].setName("111");
p[2] = new Person();
p[2].setId("aaa");
p[2].setName("222");
Arrays.sort(p);
for (Person pe : p) {
System.out.println(pe);
}
}
运行结果:
ID:aaa NAME:222
ID:bbb NAME:111
ID:bbb NAME:222