Servlet ArrayList 和 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 ; i<5 ; i++){
out.println("print data[" + i + "]" + data.get(i));
}
其结果是:
编号:0
--------------------------------------
编号:1
--------------------------------------
编号:2
--------------------------------------
编号:3
--------------------------------------
编号:4
--------------------------------------
打印数据[0]{id=4}
打印数据[1]{id=4}
打印数据[2]{id=4}
打印数据[3]{id=4}
打印数据[4]{id=4}
为什么只存储最后一个元素?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你是在问为什么 HashMap 中只存储一个值。如果是这种情况:
每次调用
Map.put("id", i)
时,您都会覆盖之前的 Key,Value 对,其中 key="id"。在地图数据结构中,键是唯一的。所以 item 只有一对 Key,Value。如果您问为什么列表中的每个元素都是相同的,正如 Nikita 所说,您每次都将完全相同的 HashMap 存储到列表中。
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
发生这种情况是因为您仅使用该项目的一个实例。
您必须在每个 while 循环中实例化该项目,如下所示。
It happens because you work with just an instance of the item.
You must instantiate the item in every while loop, like this.