Results 1 to 2 of 2
  1. #1
    guerlando is offline Member
    Join Date
    Mar 2016
    Posts
    11
    Rep Power
    0

    Default creating a list of hashmap elements through a for loop

    I'm inside a loop:
    Java Code:
    List<Map<String,String>> myList = new ArrayList<Map<String,String>>()
    
    for (...) {
            Map<String, String> messageRow = new HashMap<String, String>();
            messageRow.put("title",title);
            messageRow.put("messageId",messageId);
            messageRow.put("sentDate",sentDate);
            messageRow.put("readDate",readDate);
    //ADD Here
          }
    In the comment I made, I wanted to add this messageRow element to myList, but I have doubts about how it will work. Every time the a loop happens, will the last messageRow be erased from memory, and this new one created? If so, wouldn't the messageRow that I added to myList be erased also?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: creating a list of hashmap elements through a for loop

    Nope. You are storing a reference to the Map in the list. Then you loop and create a new Map and then store that reference in the list. Think about it this way.

    Java Code:
    Map<String, String> foo = new HashMap<>();
    Map<String,String> bar = foo;
    foo = new HashMap<>();
    At this point, bar still has the original hashmap. Assigning a new one to foo doesn't change bar. Same would be true for the list.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. adding elements to a list
    By mia69 in forum Advanced Java
    Replies: 2
    Last Post: 02-06-2014, 04:26 PM
  2. Replies: 0
    Last Post: 02-27-2012, 02:39 AM
  3. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  4. cant read xml elements into list
    By webdriver in forum New To Java
    Replies: 4
    Last Post: 08-09-2010, 08:43 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •