zozourban
zozourban

Reputation: 33

Unable to add a HashMap in an Arraylist without deleting the previous element

My Code:

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;
}

In debug, I can see each title and description in the map. When I add my map in the arrayList, all previous key-value in the arraylist are replaced by the current key-value. So at the end I have a arrayList with 20 same title and description.

How do I add several title and description in the arrayList without erasing all others?

Upvotes: 0

Views: 575

Answers (2)

Jens
Jens

Reputation: 69440

You have to create the map in the loop:

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);
    }
}

Upvotes: 0

Fortega
Fortega

Reputation: 19682

You should create a new map for each menuItem. In the example below, I moved the map initializer to the for loop:

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;
}

Upvotes: 1

Related Questions