开发者

servlet ArrayList and HashMap

List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> item = new HashMap<String, Object>();

data.clear();
item.clear();
int i = 0;
while (i < 5){
   item.put("id", i);
   i++;
   out.println("id: " + item.get("id"));
   out.println("--------------------------");
   data.add(item);
}
for(i=0 ; 开发者_如何学JAVAi<5 ; i++){
   out.println("print data[" + i + "]" + data.get(i));
}

Result of that is:

id: 0

--------------------------

id: 1

--------------------------

id: 2

--------------------------

id: 3

--------------------------

id: 4

--------------------------

print data[0]{id=4}

print data[1]{id=4}

print data[2]{id=4}

print data[3]{id=4}

print data[4]{id=4}

Why only last element is stored?


I think you're asking why there is only one value stored in your HashMap. If that's the case:

Every time you call Map.put("id", i) you are overwriting the previous Key,Value pair where key="id". In a map data structure, the keys are unique. So item has only one Key,Value pair.

If you're asking why each element in your list is the same, well as Nikita said, you're storing the exact same HashMap into your List each time.


Because you're repeatedly changing one hash map. Try creating a copy when you add it to the list

data.add(new HashMap(item));


It happens because you work with just an instance of the item.

You must instantiate the item in every while loop, like this.

while (i < 5){
    item = new HashMap<String, Object>();
    item.put("id", i);
    i++;
    out.println("id: " + item.get("id"));
    out.println("--------------------------");
    data.add(item);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜