OiRc OiRc - 4 months ago 31
Java Question

hash map and arrayList

look at this small example

import java.util.ArrayList;
import java.util.HashMap;

public class Foo {
public static void main(String[] args) {

ArrayList<Integer> array = new ArrayList<Integer>();
HashMap<String, ArrayList<Integer>> foo = new HashMap<String,ArrayList<Integer>>();

for (int i = 0; i < 20; i++)
array.add(i);

foo.put("1", array);
// array.clear();

System.out.println(foo.get("1").size());
}
}


Now, if use
array.clear()
it automatically delete all values of the arrayList associated with the specified key inside the hashmap

how can I prevent this?

in such a way that:


  • I can perform
    array.clear();
    (after entering values ​​in hashmap) and only delete the values of
    ArrayList<Integer> array

  • The values ,​​of the array associated with that key, won't deleted inside the hashmap



if you launch this program,it will print 20 without using
array.clear();
, 0 instead

Answer

It is deleting the maps keys elements because both are same objects. You have to make a shallow copy to make both lists separate

Creating a shallow copy is pretty easy though:

List<Integer> newList = new ArrayList<Integer>(oldList);

Here is the code:

public class Foo {
    public static void main(String[] args) {

        ArrayList<Integer> array = new ArrayList<Integer>();
        HashMap<String, ArrayList<Integer>> foo = new HashMap<String, ArrayList<Integer>>();

        for (int i = 0; i < 20; i++)
            array.add(i);

        ArrayList<Integer> newList = new ArrayList<Integer>(array);

        foo.put("1", newList);
        array.clear();

        System.out.println(foo.get("1").size());
    }

}