在HashMap Java中存储数据

时间:2014-02-06 19:55:14

标签: java hashmap processing

我正在尝试将数据存储在HashMap中,但我似乎只能将我正在读取的数据源的最后一项存储到HashMap中,我不确定为什么。

以下是我的代码:

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

这一行 - &gt; 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中。

这一行 - &gt; println(t);输出:

{name=Wicklow, pop=136,640}

非常感谢有关此事的帮助。基本上它只是将数据列表放入hashmap中,而且目前只放入该列表中的最后一项。

2 个答案:

答案 0 :(得分:3)

如果您要打印每个properties的{​​{1}},请将Marker行移至for循环中,因为此时println(t)将指向上次使用的element的属性,因为你只是重新分配它; s值循环的每次迭代。要t地图中的元素,请使用putput(Key, Value)方法

答案 1 :(得分:0)

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

相关问题