Java 如果不删除上一个元素,则无法在Arraylist中添加HashMap
我的代码:Java 如果不删除上一个元素,则无法在Arraylist中添加HashMap,java,android,collections,arraylist,Java,Android,Collections,Arraylist,我的代码: public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc, XMLParser file) { Map<String, String> map = new HashMap<String, String>(); ArrayList<Map<String, String>> menuItems
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc,
XMLParser file) {
Map<String, String> map = new HashMap<String, String>();
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for (int i = 0; i < Doc.getElementsByTagName("item").getLength(); i++) {
Element e = (Element) Doc.getElementsByTagName("title").item(i);
Element e2 = (Element) Doc.getElementsByTagName("description")
.item(i);
// Element e3 = (Element)Doc.getElementsByTagName("link").item(i);
map.put("titre", file.getElementValue(e));
map.put("description", file.getElementValue(e2));
// map.put("lien", file.getElementValue(e3));
// adding HashList to ArrayList
menuItems.add(map);
}
return menuItems;
}
public ArrayList XMLToArray(字符串数据、文档文档、,
XMLParser文件){
Map Map=newhashmap();
ArrayList menuItems=新建ArrayList();
对于(int i=0;i
在调试中,我可以看到地图中的每个标题和描述。在arrayList中添加贴图时,arrayList中以前的所有键值都将替换为当前键值。
最后我有一个arrayList,有20个相同的标题和描述
如何在arrayList中添加多个标题和说明,而不删除所有其他标题和说明?您应该为每个菜单项创建一个新的映射。在下面的示例中,我将映射初始值设定项移动到for循环:
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc, XMLParser file)
{
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for(int i = 0; i < Doc.getElementsByTagName("item").getLength();i++)
{
Map<String, String> map = new HashMap<String, String>();
Element e = (Element)Doc.getElementsByTagName("title").item(i);
Element e2 = (Element)Doc.getElementsByTagName("description").item(i);
//Element e3 = (Element)Doc.getElementsByTagName("link").item(i);
map.put("titre", file.getElementValue(e));
map.put("description", file.getElementValue(e2));
//map.put("lien", file.getElementValue(e3));
// adding HashList to ArrayList
menuItems.add(map);
}
return menuItems;
}
public ArrayList XMLToArray(字符串数据、文档文档、XMLParser文件)
{
ArrayList menuItems=新建ArrayList();
对于(int i=0;i
您必须在循环中创建映射:
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc, XMLParser file) {
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for(int i = 0; i < Doc.getElementsByTagName("item").getLength(); i++) {
Map<String, String> map = new HashMap<String, String>();
Element e = (Element)Doc.getElementsByTagName("title").item(i);
}
}
public ArrayList XMLToArray(字符串数据、文档文档、XMLParser文件){
ArrayList menuItems=新建ArrayList();
对于(int i=0;i
您多次将同一对象添加到列表中,您认为它会有什么不同?谢谢大家,它工作得很好!但我不明白为什么我需要创建每个对象,我不能只使用一个对象映射并更改属性?不,你不能。实际上,您正在向ArrayList添加对映射的引用。如果只有一个映射,ArrayList将填充指向同一映射的引用。