调用java.util.Collections.sort(List list)方法来进行排序的时候,List内的Object都必须实现了Comparable接口,否则会报ClassCastException错。
或用java.util.Collections.sort(List list,Comparator c),临时声明一个Comparator来实现排序
package com.my.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 使用Comparator对List排序
*/
public class ListSort {
static List<Person> personList = new ArrayList<Person>();
public static void initList() {
personList.add(new Person("a",15,"123"));
personList.add(new Person("c",16,"123"));
personList.add(new Person("j",17,"123"));
personList.add(new Person("d",21,"123"));
personList.add(new Person("b",18,"123"));
}
public static void main(String[] args) {
initList();
for (int i = 0; i < personList.size(); i++) {
System.out.println(personList.get(i));
}
System.out.println("======================================");
//默认排序,
Collections.sort(personList);
for (int i = 0; i < personList.size(); i++) {
System.out.println(personList.get(i));
}
System.out.println("======================================");
//实现接口Comparator自定义排序
Collections.sort(personList,new Comparator<Person>() {
//按年龄排序
@Override
public int compare(Person o1, Person o2) {
int flag = 0;
if (o1.getAge()>o2.getAge()) {
flag = 1;
} else if (o1.getAge()<o2.getAge()) {
flag = -1;
}
return flag;
}
});
for (int i = 0; i < personList.size(); i++) {
System.out.println(personList.get(i));
}
}
}
class Person implements Comparable<Person> {
private String name;
private int age;
private String cardid;
public Person() {
}
public Person(String name, int age, String cardid) {
this.name = name;
this.age = age;
this.cardid = cardid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCardid() {
return cardid;
}
public void setCardid(String cardid) {
this.cardid = cardid;
}
public String toString() {
return this.name+","+this.age+","+this.cardid;
}
public int compareTo(Person p) {
// TODO Auto-generated method stub
return this.name.compareTo(p.getName());
}
}