Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap updating ArrayList

I'm just starting to learn to use HashMap and reading the java tutorial, but I'm having trouble.

I'm trying to update the List inside a HashMap but I want to get the List of that key, is there a way to update a specific List of the key instead of having to make...5 different Lists and updating those?

 HashMap<String, ArrayList<String>> mMap = new HashMap<String, ArrayList<String>>();
        ArrayList<String> list = new ArrayList<String>();
        mMap.put("A", list);
        mMap.put("B", list);
        mMap.put("C", list);
        mMap.put("D", list);

        Iterator iter = mMap.entrySet().iterator();

        if (mMap.containsKey("A"))
        {   
            Map.Entry mEntry = (Map.Entry) iter.next();
            list.add("test");
            mMap.put("A",list);
            System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
        else if (mMap.containsKey("B"))
        {   
            Map.Entry mEntry = (Map.Entry) iter.next();
            list.add("entry");
            mMap.put("B",list);
            System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
        }
like image 509
Thao Nguyen Avatar asked Dec 01 '11 18:12

Thao Nguyen


2 Answers

You could use something like:

mMap.get("A").add("test");
mMap.get("B").add("entry");
like image 57
Tudor Avatar answered Oct 18 '22 15:10

Tudor


If you add the same list as a value with different keys, in your case keys A,B,C, and D all point to the same list, and access and update the list through one key the changes will then be visible in all the lists. Each key points to the same list structure.

If you want the lists to be different you need to use different for different keys you need to use a different list.

You could automate the process, say by making your own insert method that clones the given list.

like image 36
Paul Rubel Avatar answered Oct 18 '22 13:10

Paul Rubel