servlet ArrayList and HashMap problem witch result
Posted
by
nonameplum
on Stack Overflow
See other posts from Stack Overflow
or by nonameplum
Published on 2011-01-06T00:38:37Z
Indexed on
2011/01/06
0:53 UTC
Read the original article
Hit count: 142
Hi, I have that code
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 ; i<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?
© Stack Overflow or respective owner