CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2006
    Posts
    22

    LinkedHashMap vs ArrayList.clear()

    Hi All, I need a help on my code.
    I have put an arraylist as a value in to a map.But when I cleared the arraylist the value of map also removed. and after clear the arraylist when I put same arraylist with new entry and put on map for different key it behave unexpectedly.

    please suggest me on this.


    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;

    public class fullTest1
    {
    public static void main(String[] args)
    {
    LinkedHashMap<String, List> hashMap = new LinkedHashMap<String, List>();
    ArrayList<String> arrlist1 = new ArrayList<String>();

    arrlist1.add("a");
    arrlist1.add("b");
    arrlist1.add("c");
    arrlist1.add("d");
    hashMap.put("1", arrlist1);
    System.out.println("Map Before ArrayList clear:"+hashMap);

    arrlist1.clear();

    System.out.println("Map After ArrayList clear:"+hashMap);

    arrlist1.add("a");
    hashMap.put("2", arrlist1);
    System.out.println("Map with new Key:"+hashMap);
    }
    }
    -----------
    Out Put is:

    Map Before ArrayList clear:{1=[a, b, c, d]}
    Map After ArrayList clear:{1=[]}
    Map with new Key:{1=[a], 2=[a]}

  2. #2
    Join Date
    Oct 2008
    Posts
    77

    Re: LinkedHashMap vs ArrayList.clear()

    putting in hash map puts reference to original object, not deep copy of it, so any changes to object itself will propagate to objects retrieved from hash map

  3. #3
    Join Date
    Jan 2006
    Posts
    22

    Re: LinkedHashMap vs ArrayList.clear()

    Thanks for reply; I tried to put the clone of ArrayList as following and it working as expected.
    But is it the only way or there are any other way I can do. please suggest me.

    hashMap.put("1", (List) arrlist1.clone());
    Instead of
    hashMap.put("1", arrlist1);
    -----------
    out put is:

    Map Before ArrayList clear:{1=[a, b, c, d]}
    Map After ArrayList clear:{1=[a, b, c, d]}
    Map with new Key:{1=[a, b, c, d], 2=[a]}

  4. #4
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: LinkedHashMap vs ArrayList.clear()

    But is it the only way or there are any other way I can do. please suggest me.
    You can also do:
    Code:
    hashMap.put("1", new ArrayList(arrlist1));

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured