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]
[]