0

我首先开始使用单个 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;
        }
    }
}

问题:现在我有超过 2 个新的 Hash Maps 以相同的方式排序,而不是复制ValueComparator4Broker类的代码,我想制作一个可以被所有新的 *HashMap*s 使用的通用和参数化ValueComparator类:

private static Map<Area, Integer> areaBrokerCountList = new HashMap<Area, Integer>();
private static Map<Area, Integer> areaSalesTotalList = new HashMap<Area, Integer>();

我尝试了类似以下的方法,但代码是错误的,甚至不接受要替换Type的 HashMap 的关键对象。任何有助于改进该方法和代码示例的帮助将不胜感激:

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
    }

}
4

1 回答 1

1

我不太擅长冷输入通用代码,但我的想法是:

以这种方式使用类:

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
    }

}
于 2013-07-08T18:20:43.747 回答