我第一次开始使用单个HashMap,例如:
private static Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();
并使用
private static ValueComparator4Broker bvc = new ValueComparator4Broker(brokerSalesCountList);
private static TreeMap<Broker,Integer> sortedbrokerSalesCountList = new TreeMap<Broker,Integer>(bvc);
sortedbrokerSalesCountList.putAll(brokerSalesCountList);
这是我的值比较器代码:
public class ValueComparator4Broker implements Comparator<Broker> {
Map<Broker, Integer> base;
public ValueComparator4Broker(Map<Broker, Integer> base) {
this.base = base;
}
@Override
public int compare(Broker a, Broker b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
}
}
}
问题:现在我有两个以上的新哈希映射要以相同的方式排序,并且我不想复制ValueComparator4Broker类的代码,而是想创建一个通用的参数化ValueComparator,它可以被所有新的*HashMap*s:使用
private static Map<Area, Integer> areaBrokerCountList = new HashMap<Area, Integer>();
private static Map<Area, Integer> areaSalesTotalList = new HashMap<Area, Integer>();
我尝试了如下操作,但代码是错误的,甚至不接受用HashMap的键对象来代替Type。任何对改进方法和代码示例的帮助都将不胜感激:
import java.lang.reflect.Type;
import java.util.Comparator;
import java.util.Map;
public class ValueComparator implements Comparator<Type> {
Map<Type, Integer> base;
public ValueComparator(Map<Type, Integer> base) {
this.base = base;
}
@Override
public int compare(Type a, Type b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
我不太擅长冷输入泛型代码,但我的想法是:
这样使用类:
Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();
private static ValueComparator<Broker> bvc = new ValueComparator<Broker>(brokerSalesCountList);
在此处定义类:
public class ValueComparator<T> implements Comparator<T> {
Map<T, Integer> base;
public ValueComparator(Map<T, Integer> base) {
this.base = base;
}
@Override
public int compare(T a, T b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}