2014-02-06 43 views
0

我想将数据存储在HashMap中,但是我似乎只能将数据源的最后一项存储到HashMap中,我不确定为什么。在HashMap中存储数据Java

下面是我的代码:

//Loops through the counties and stores the details in a Hashmap 
void getCountyDetails(List<Marker>m){ 
    HashMap t = new HashMap(); 
    for(Marker county: countyMarkers){ 
    println("county:" + county.getProperties()); 
    t = county.getProperties(); 
    } 
    println(t); 
} 

这行 - >println("county:" + county.getProperties());

输出这样的:

county:{name=Carlow, pop=54,612} 
county:{name=Cavan, pop=73,183} 
county:{name=Clare, pop=117,196} 
county:{name=Cork, pop=519,032} 
county:{name=Donegal, pop=161,137} 
county:{name=Dublin, pop=1,273,069} 
county:{name=Galway, pop=250,541} 
county:{name=Kerry, pop=145,502} 
county:{name=Kildare, pop=210,312} 
county:{name=Kilkenny, pop=95,419} 
county:{name=Laois, pop=80,559} 
county:{name=Letrim, pop=31,796} 
county:{name=Limerick, pop=191,809} 
county:{name=Longford, pop=39,000} 
county:{name=Louth, pop=122,897} 
county:{name=Mayo, pop=130,638} 
county:{name=Meath, pop=184,135} 
county:{name=Monaghan, pop=60,483} 
county:{name=Offaly, pop=76,687} 
county:{name=Roscommon, pop=64,065} 
county:{name=Sligo, pop=65,393} 
county:{name=Tipperary, pop=158,754} 
county:{name=Waterford, pop=113,795} 
county:{name=Westmeath, pop=86,164} 
county:{name=Wexford, pop=145,320} 
county:{name=Wicklow, pop=136,640} 

我想将它们存储在HashMap

这行 - >println(t);输出:

{name=Wicklow, pop=136,640} 

希望了解对此事的人的帮助。基本上,它只是获取数据的列表到HashMap中,目前仅在该列表中的最后一个项目被加入到。

+0

那么你的'HashMap.put'方法调用在哪里? –

回答

3

如果你要打印的每个Markerproperties,移动println(t)行成for循环,因为目前t将指向最后使用的元素的属性,因为您只需重新分配它; s值是循环的每次迭代。若要put地图中的元素,请使用put(Key, Value)putAll()方法代替

0

在java中,您应该使用hashMap.put(key,value)将新项添加到哈希映射中。 在你的代码中,你写了HashMap t = new HashMap(); t = county.getProperties();所以你的地图价值实际上每次都被重新分配到乡村房产。