Saturday, April 18, 2020

Java puzzle – TreeMap put operation

Puzzle : I have given a below map with the following below options,
Map map = new TreeMap();
map.put("test key 1", "test value 1");
map.put("test key 2", "test value 2");
map.put("test key 3", "test value 3");
  
System.out.println(map.put("test key 3", "test value 3"));
System.out.println(map.put("test key 4", "test value 4"));
Option A) System.out.println(map.put(“test key 3”, “test value 3”));
Answer) This prints the output as = test value 3
Option B) System.out.println(map.put(“test key 4”, “test value 4”));
Answer) This prints the output as = null;
Can anyone please explain why option b is giving us such a behavior?
Also when I print the map after the Option B sysout statement, I have the test key 4 present in it?
Solution : If you look at Map.put() operation, it returns the value if key is already present in map.
After adding key “test key 3”, when again try to add it, it returns the value “test value 3”.
When you add “test key 4” first time, it is no present in map, so map return’s it’s value is null.
Next time when you store “test key 4”, this time entry is already present so value is returned as “test value 4”

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...