研究了几天,那时候就是认为要继承Comparable接口,重写CompareTo方法,结果走向了歧路.后来就搜啊搜,发现了点东西.自己又总结了下.需要的JAR包:commons.collections.jar
package test;
import java.util.Collections;
import java.util.Comparator;
import java.util.ArrayList;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
public class CompareTipA {
private int id;
private String name;
private String age;
public static void main(String []args) {
ArrayList<Object> list = new ArrayList<Object>();
list.add(new CompareTipA(1,"3","五"));
list.add(new CompareTipA(1,"1","六"));
list.add(new CompareTipA(1,"5","二"));
list.add(new CompareTipA(1,"4","四"));
list.add(new CompareTipA(4,"2","一"));
Comparator mycmp = ComparableComparator.getInstance();
mycmp = ComparatorUtils.nullLowComparator(mycmp); //允许null
mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add(new BeanComparator("id", mycmp)); //id逆序 (主)
sortFields.add(new BeanComparator("name")); //name正序 (副)
ComparatorChain multiSort = new ComparatorChain(sortFields);
Collections.sort(list,multiSort);
for (int i =0;i<list.size();i++) {
System.out.println(list.get(i)); //输出
}
}
public CompareTipA(int id, String name,String age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// public int compareTo(Object o) {
// return this.comparator.compare(this, o);
// }
public String toString() {
return "[id=" + this.id + ",name=" + this.name +",age=" + this.age +"]";
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}