I am having trouble understanding some simple code relating with Lists and maps. Take the code below as an example:
public class test {
private Map<Integer, List<String>> myMap ;
public test(){
myMap = new HashMap<Integer, List<String>>();
}
public void addToMap(String ss){
List<String> myTemp = myMap.get(ss);
Random r = new Random();
if(myTemp == null){
myTemp = new ArrayList<String>();
myMap.put(r.nextInt(100), myTemp);
}
myTemp.add(ss);
}
public Map<Integer, List<String>> getMap1(){
return myMap;
}
public static void main(String args[]){
test myTest = new test();
myTest.addToMap("abdc");
myTest.addToMap("eeer");
System.out.println(myTest.getMap1());
}
}
How exactly does the addToMap() add a new element to the mylist Map. More specifically, how does myTemp.add(ss) add a new element to myMap when myTemp is a local variable and gets deleted once its done executing. Moreover, removing myTemp.add(ss) from the addToMap() method prints out an empty HashMap in the main method, why is this? How does the put method insert the element into the map when it is executed before the add method? Thanks.
Edit: I edited the code to make a little more sense.
Unlike C++, in Java all variables are references to the real objects. So, when you do
you create an object in the heap whose reference is copied to the stack variable myTemp. If the reference is added to the list (or other variable), a copy of the reference is added there.
Once myTemp is destroyed, the object continues alive. The exception is when all the references to the object are gone; then the object can not be reached by the code and Garbage Collection can (but it is not forced to) delete it from memory.