============ Problem Description ============
The following code has been running well, but suddenly something went wrong. Listall.add should have been added to each MAP2, but the output has become the same map2. Been running well before, what's going on here?
Listall.clear ();for (int i = 0; i < str.length / 8; i++) {system.out.println ("i = " + i); Map2.put ("User_name", list.get (i * 8) ); Map2.put ("Flag", list.get (i * 8 + 1)); Map2.put ("Object_words", list.get (i &NBSP;*&NBSP;8&NBSP;+&NBSP;2) map2.put ("My_words", list.get (i * 8 + 3)); Map2.put (" Date ", list.get (i * 8 + 5));// If the user does not pass a photo, ImageUrl in Map2 is empty if (!list.get (i * 8 + 4). Equals (" ")) {String imageUrl1 = "http://10.0.2.2:8080/ bbstuservlet/"+ list.get (i * 8 + 4); String imageurl = imageurl1.replace (" ", ""); Map2.put ("ImageUrl", imageurl);} else {map2.put ("ImageUrl", "");} System.out.println ("map2 = " + map2); Listall.add (MAP2); System.out.println ("listall = " + listAll);
Below this picture is the output, Listall inside the value all is the same, before also runs normally, please elder's advice, grateful.
============ Solution 1============
You put the MAP2 instantiation in the For loop (that is, every time the loop is a new MAP2), it should be fine.
============ Solution 2============
The value of the variable MAP2 does not change, so you add the same object each time, and each time you modify the same object by put.
A new object should be in each loop
for (int i = 0; i < STR.LENGTH/8; i++) {map2 = new hashmap<string, string> (); ...}
List.add Issues in Android