Tuesday, August 27, 2013

I do not understand my output. Why am I getting the same thing twice?

I do not understand my output. Why am I getting the same thing twice?

The following program maintains 2 data structures named:
map of type HashMap
map_1 also of type HashMap
At the beginning map is populated with key : 1 and value : suhail. Then
this map is inserted into map_1 with key 20.
Again the map is populated with key : 1 and another value : CSE. This map
is again inserted into map_1.
import java.util.*;
class KeyTest {
public static void main(String args[]) {
Map<Integer,String> map = new HashMap<Integer,String>();
Map<Integer,Object> map_1 = new HashMap<Integer,Object>();
map.put(1,"suhail");
map_1.put(20,map);
map.put(1,"CSE");
map_1.put(21,map);
Set<Integer> keys = map_1.keySet();
Iterator i = keys.iterator();
while(i.hasNext()) {
System.out.println(map_1.get((Integer)i.next()));
}
}
}
This is what I get, when I print map_1 values :
{1=CSE}
{1=CSE}
But this is not, what I expected.According to me this is how the program
should have been running :
[1,suhail]--> map
[20,[1,suhail]]---> map_1
[1,CSE]--> map (A replace, because of the same keys)
[21,[1,CSE]]--->map_1
So the output should have been :
[1,suhail]
[1,CSE]
Can anyone please explain me, why don't I get this output

No comments:

Post a Comment