0

我有这张地图:

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

我使用此函数填充此地图:

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 值只需要一个元素!我已经在调试模式下执行了很多次,但看不到为什么只能添加一个项目。请你检查一下吗?

4

2 回答 2

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);
于 2013-11-14T12:18:41.487 回答
0

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

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

  2. 'cityIndi​​vidualMap' 的声明不一致(Treeset 与 hashmap),我假设它是一个 HashMap,基于您对它的使用

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

于 2013-11-14T12:39:23.473 回答