ArrayList , and HashMap

I am having this problem that has got me stumped. I have a HashMap holding a map of a list, I then copy the list and put it into an ArrayList variable. However whenever I edit the ArrayList variable the map of the list is also being edited in the HashMap. If someone could help explain this, and how to prevent it from occurring, it would be greatly appreciated!

import java.util.*;

public class HashMapTest{

public static void main(String args[]){
HashMap<String, ArrayList<String>> actors = new HashMap<String, ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> tempList = new ArrayList<String>();

tempList.add("1");

//Key: First, Map: 1
actors.put("First", tempList);

//List = 1
list = actors.get("First");

//List = 1,2
list.add("2");

System.out.println(actors);
//List = null
list.clear();
System.out.println(actors);

}

}

Output:
[1,2]
[]

This happens because in Java when you have an Object it’s actually a reference to where that object is in memory. So when you add the list to the HashMap you now have a reference to that same list in the list variable and in the HashMap. You can fix this by doing something like this:


// Copy the list into the HashMap
actors.put("First", (ArrayList<String>)  tempList.clone());

// Or...

//Copy the list out of the HashMap
list = (ArrayList<String>) actors.get("First").clone();

Thanks! Wished I had asked a lot sooner, spent a few hours figuring this out.