在下面的for循环中:
for(int i = 0; i < initialSplit.length; i++){ //initialSplit - contains one DB record (row)
String [] cellVal = (initialSplit[i]).split("~");
System.out.println(cellVal[0]);
for(int j = 0; j < cellVal.length; j++){ //cellVal - contains value of each cell in a record
map.put(dataIndexString[j], cellVal[j]);
System.out.println(j+"--"+dataIndexString[j] + " -- key : value -- "+cellVal[j]);
}
items.add(map);//The last record alone adds into the ArrayList 'items'
}
initialSplit
的长度为10(10条记录),cellVal.length
为21条。
将HashMap
添加到ArrayList
后,最后一张地图会被添加10次,而不是10张地图,每次添加一次。我也试过map.clear()
,但可能在错误的地方
我无法发现错误。有人可以帮帮我吗?
答案 0 :(得分:4)
只有一个地图实例可以多次添加到列表中。
为了将差异贴图添加到列表中,您必须创建多个实例:
map = new HashMap<...>();
for(int j = 0; j < cellVal.length; j++){ //cellVal - contains value of each cell in a record
map.put(dataIndexString[j], cellVal[j]);
System.out.println(j+"--"+dataIndexString[j] + " -- key : value -- "+cellVal[j]);
}
items.add(map);