开发者

Why is my nested hashmap setting all the values to the same thing?

This is my first foray into java, and I am having trouble understanding how maps work. I have a for loop which appends maps of information into another map. However when I look at the outermost map it contains the correct number of sub-maps, however they all conatin the same information, even though I originally put different information in them... does anyone know why?

Thanks,

Lemiant

Below I have included my code and the System.out.print output:

Code:

Map contin开发者_如何学Goents = new HashMap();
Map continentData = new HashMap();
int lastContinent = -1;


//Accumulate Continent data
for(Country currCountry : countries){
    continentData.clear();
    int currContinent = currCountry.getContinent();

    continentData.put("P", 0);
    continentData.put("E", 1);
    continentData.put("O", 2);
    continentData.put("Bonus",currContinent);

    if(currContinent != lastContinent){
        continents.put(currContinent, continentData);
        System.out.println("add");
        System.out.println(continentData);
    }

    lastContinent = currContinent;
}

System.out.println(continents.toString());

Result:

add
{E=1, P=0, O=2, Bonus=0}
add
{E=1, P=0, O=2, Bonus=1}
add
{E=1, P=0, O=2, Bonus=2}
add
{E=1, P=0, O=2, Bonus=3}
add
{E=1, P=0, O=2, Bonus=4}
add
{E=1, P=0, O=2, Bonus=5}
{0={E=1, P=0, O=2, Bonus=5}, 1={E=1, P=0, O=2, Bonus=5}, 2={E=1, P=0, O=2, Bonus=5}, 3={E=1, P=0, O=2, Bonus=5}, 4={E=1, P=0, O=2, Bonus=5}, 5={E=1, P=0, O=2, Bonus=5}}


You need to move Map continentData = new HashMap(); inside your for loop so that a separate map is created on each pass. Right now you're just updating the same map over and over.


You are using the same instance of continentData for all the maps. You must instantiate a new Map for it in each loop interation.

for(Country currCountry : countries){
    //continentData.clear();
    Map continentData = new HashMap();
    int currContinent = currCountry.getContinent();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜