简体   繁体   English

无法填充以TreeSet作为参数的HashMap

[英]Unable to populate a HashMap that has a TreeSet as a parameter

I have this Map: 我有这张地图:

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

I populate this Map using this function: 我使用以下功能填充此地图:

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);
        }
    }
} 

This is my Comparator: 这是我的比较器:

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;
    }
}

The individual class is just a data class.. so I wont copy it over here. 单个类只是一个数据类..所以我不会在这里复制它。

For some very odd reason the CityIndividualMaps value only takes one element! 由于某些非常奇怪的原因,CityIndi​​vidualMaps值仅包含一个元素! I have executed this on debug mode many times but cannot see why only one item can be added.. Please could you check it out? 我已经在调试模式下执行了很多次,但是看不到为什么只能添加一项​​。.请检查一下吗?

You keep overwriting every city's individual list with a new one. 您会用新清单继续覆盖每个城市的清单。 Change: 更改:

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);

To: 至:

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

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

Weird, I ran your code and it sort of worked, with the following exceptions: 很奇怪,我运行了您的代码,并且工作正常,但以下情况除外:

  1. There seems to be a mixup between 'individualList' and 'individualSet' 在“ individualList”和“ individualSet”之间似乎存在混淆

  2. The declaration of 'cityIndividualMap' is inconsistent (Treeset versus hashmap), I assumed it's a HashMap based on your usage of it “ cityIndi​​vidualMap”的声明不一致(树集与哈希图),根据您的使用情况,我认为它是一个HashMap

  3. class "City" should have hashCode + equals, otherwise you can get find several keys with the same City “ City”类应具有hashCode +等于,否则您可以找到具有相同City的多个键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM