无法填充具有TreeSet作为参数的HashMap

时间:2013-11-14 12:05:52

标签: java hashmap populate treeset sortedset

我有这张地图:

Map<City, TreeSet<Individual>> cityIndividualMap = new HashMap<City, TreeSet<Individual>>();

我使用此函数填充此Map:

public void add(List<Individual> individuals){
    for (Individual individual : individuals){
        individualSortedSet.add(individual);

        for(City city:individual.getCities()){
            TreeSet<Individual> individualList;

            if (cityIndividualMap.containsKey(city))
                individualSet = cityIndividualMap.get(city);
            else
                individualSet = new TreeSet<Individual>( new FitnessComparator());

            individualSet.add(individual);
            cityIndividualMap.put(city, individualSet);
        }
    }
} 

这是我的比较者:

public class FitnessComparator implements Comparator<Individual> {
    @Override
    public int compare(Individual individual1, Individual individual2) {
        if (individual1.getFitness() == individual2.getFitness())
            return 0;
        return (individual1.getFitness() > individual2.getFitness())? 1 : -1;
    }
}

单个类只是一个数据类..所以我不会在这里复制它。

由于一些非常奇怪的原因,CityIndi​​vidualMaps值只需要一个元素!我已多次在调试模式下执行此操作,但无法理解为什么只能添加一个项目..请问您能查看一下吗?

2 个答案:

答案 0 :(得分:1)

你会用新的名单覆盖每个城市的个人名单。变化:

TreeSet<Individual> individualList;

if (cityIndividualMap.containsKey(city))
    individualSet = cityIndividualMap.get(city);
else
    individualSet = new TreeSet<Individual>( new FitnessComparator());

individualSet.add(individual);
cityIndividualMap.put(city, individualSet);

要:

TreeSet<Individual> individualList = cityIndividualMap.get(city);

if (individualList == null)
{
    individualList = new TreeSet<Individual>( new FitnessComparator());
    cityIndividualMap.put(city, individualList);        
}
individualList.add(individual);

答案 1 :(得分:0)

很奇怪,我运行了你的代码并且它有点工作,但有以下例外:

  1. 'individualList'和'individualSet'之间似乎有混淆

  2. 'cityIndi​​vidualMap'的声明不一致(Treeset与hashmap),我认为它是基于你使用它的HashMap

  3. 类“City”应该有hashCode + equals,否则你可以找到同一个城市的几个键