您可以声明一个优先级哈希映射:
private static final HashMap<String,Integer> PRIORITIES = new HashMap<String, Integer>();
static{
PRIORITIES.put("A", 1);
PRIORITIES.put("B", 1);
PRIORITIES.put("C", 1);
PRIORITIES.put("D", 1);
PRIORITIES.put("E", 2);
PRIORITIES.put("F", 2);
PRIORITIES.put("G", 3);
}
然后实现compare
你的方法Comparator
:
private int getPriority(CustomClass obj) {
if(obj!=null&&PRIORITIES.containsKey(obj.getType())) {
priority1 = PRIORITIES.get(obj.getType());
} else {
priority1 = Integer.MAX_VALUE;
}
}
@Override
public int compare(CustomClass o1, CustomClass o2) {
int priority1,priority2;
priority1 = getPriority(o1);
priority2 = getPriority(o2);
return priority1==priority2 ? 0 : (priority1<priority2 ? -1 : 1);
}
更新:更清洁的方法是在您的基类(getType
声明的位置)中定义哈希图并实现getPriority
方法:
public int getPriority() {
return PRIORITIES.containsKey(getType()) ? PRIORITIES.get(getType()) : Integer.MAX_VALUE;
}
那么Comparator
很明显:
@Override
public int compare(CustomClass o1, CustomClass o2) {
int priority1,priority2;
priority1 = o1==null ? Integer.MAX_VALUE : o1.getPriority();
priority2 = o2==null ? Integer.MAX_VALUE : o2.getPriority();
return priority1==priority2 ? 0 : (priority1<priority2 ? -1 : 1);
}