package com.weina.utils;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import com.weina.PymkItemVO;
public class PymkItemTypeComparator implements Comparator<PymkItemVO> {
private int[] TYPE_ORDER = {1,16,8,2,4}; //按照指定的这个排序
public PymkItemTypeComparator() {
}
/**
* 是否倒序
* @param desc
*/
public PymkItemTypeComparator(boolean desc) {
if (desc) {
int[] temp = new int[TYPE_ORDER.length];
for (int i=0; i<TYPE_ORDER.length; i++) {
temp[i] = TYPE_ORDER[TYPE_ORDER.length - i - 1];
}
TYPE_ORDER = temp;
}
}
@Override
public int compare(PymkItemVO o1, PymkItemVO o2) {
for (int type : TYPE_ORDER) {
int type1 = o1.getType() & type;
int type2 = o2.getType() & type;
System.out.println("type="+type+";type1="+type1+";type2="+type2);
if (type1 != type2) {
return type2 - type1;
}
}
return 0;
}
public static void main(String[] args) {
List<PymkItemVO> pymkList = new LinkedList<PymkItemVO>();
PymkItemVO item = new PymkItemVO();
item.setStatus("n");
item.setType(4);
item.setUserId(11);
pymkList.add(item);
item = new PymkItemVO();
item.setStatus("n");
item.setType(2);
item.setUserId(22);
pymkList.add(item);
item = new PymkItemVO();
item.setStatus("n");
item.setType(16);
item.setUserId(33);
pymkList.add(item);
item = new PymkItemVO();
item.setStatus("n");
item.setType(1);
item.setUserId(44);
pymkList.add(item);
item = new PymkItemVO();
item.setStatus("n");
item.setType(8);
item.setUserId(55);
pymkList.add(item);
System.out.println(pymkList);
Collections.sort(pymkList, new PymkItemTypeComparator());
System.out.println(pymkList);
Collections.sort(pymkList, new PymkItemTypeComparator(true));
System.out.println(pymkList);
System.out.println("=================");
int a = 8;
int[] TYPE_ORDER = {1,8,2,4};
for (int type : TYPE_ORDER) {
System.out.print(a & type);
System.out.print(" ");
}
System.out.println("=================");
}
}
关于Comparator 按指定的顺序 排序
最新推荐文章于 2024-05-12 22:43:34 发布