List.add Issues in Android

Source: Internet
Author: User

============ 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.