Friday, 6 September 2013

How does the LinkedList inside the Map change?

How does the LinkedList inside the Map change?

In the following code,I create a map that accepts LinkedList as its value.
Using a particular key I get the LinkedList, modify it and print the
values to check if it was modified.
As the values get printed, I see it modified. But I don't expect the
values inside the LinkedList to change until I do,
map.put(for_the_same_key,modified_list) // so that old key gets replaced
by this
Why does the LinkedList inside the map change when I modified a new
LinkedList.
import java.util.*;
class MapTester {
public static void main(String args[]) {
Map<Integer,LinkedList<String>> map = new
HashMap<Integer,LinkedList<String>>();
LinkedList<String> list = new LinkedList<String>();
list.add("Suhail");
list.add("Gupta");
list.add("CSE");
map.put(1,list);
LinkedList<String> newList = map.get(1);
newList.add(2,"Khayal");
newList.remove(3);
LinkedList<String> newListAg = map.get(1);
for(String s : newListAg) {
System.out.println(s);
}
}
}

No comments:

Post a Comment