一个比较器,为了做排序对象所用,一个通用的例子
public interface Order {
public long getOrderIndex() ;
}
import java.util.Comparator;
/**
* 升序排序
*
*/
public class OrderAscStorComparator implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
if (o1.getOrderIndex() > o2.getOrderIndex()){
return 1;
}else if(o1.getOrderIndex() < o2.getOrderIndex()){
return -1;
}else{
return 0;
}
}
}
import java.util.Comparator;
/**
* 降序排序
*
*/
public class OrderDescStorComparator implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
if(o1.getOrderIndex() > o2.getOrderIndex()){
return -1;
}else if(o1.getOrderIndex() < o2.getOrderIndex()){
return 1;
}else{
return 0;
}
}
}
当需要排序的时候,实现order这个接口,并实现相应的接口方法即可实现排序规则
package com.vipshop.gmj.server.access.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.math.RandomUtils;
import com.vipshop.gmj.server.framework.util.Order;
import com.vipshop.gmj.server.framework.util.OrderDescStorComparator;
/**
* 排序测试
* @author Administrator
*
*/
public class OrderTest {
public static void main(String[] args) {
List<TestBean> beanList = new ArrayList<TestBean>();
for(int i=0;i<10;i++){
TestBean bean = new TestBean();
bean.setIdlong(RandomUtils.nextLong());
beanList.add(bean);
}
Collections.sort(beanList,new OrderDescStorComparator());
for(int i=0;i<beanList.size() ;i++){
TestBean bean = beanList.get(i);
System.out.println(bean.getIdlong());
}
}
}
class TestBean implements Order{
private long idlong;
public long getIdlong() {
return idlong;
}
public void setIdlong(long idlong) {
this.idlong = idlong;
}
@Override
public long getOrderIndex() {
return this.idlong;
}
}