Hi Team,

Im reading collections and there is a topic called Backed Collections. I could not understand the output below . Please throw some light on it.

TreeMap<String,String> map = new TreeMap<String,String>();

SortedMap<String,String> submap;
submap = map.subMap("b","g");

System.out.println(map + " " + submap);

map.put("b", "bat");

map.put("r", "raccoon");

// submap.put("p" , "pig");  // out of range

System.out.println(map + "  " + submap);

** OUTPUT **

{a=ant, d=dog, h=horse}  {d=dog}
{a=ant, b=bat, d=dog, f=fish, h=horse, r= racoon} { b=bat, d=dog, f=fish}

Please explain the output and one comment inside the code which says "out of Range".

TreeMaps are always sorted by their keys.
subMap returns a view of a contiguous range of keys of the TreeMap, including only those keys within the specified range.
Because it's a view, updates to it just update the origional (backing) TreeMap.
Similarly updates to the origional TreeMap arre immediate visible in the view (provided they are inside the range specified when the subMap as created).
Because the view is only a specified range of keys, any attempt to add a key to it must be within that range. Anything outside that is an error.

oh ok . so i have intialised as

submap = map.subMap("b","g");

So what is the range here ? is the range is like, "b" is the second alphabet so i can add ony two elements in the submap ?. is that what range here means?

The range of keys that will be included in the subMap view are from "b" to "g". That includes all possible keys that sort after "b" but before "g". You can add any keys within that range, but not ouside it. "b" being the second letter in the alphabet has no significance whatsoever.

ps: Technically speaking the range is from "b" inclusive to "g" exclusive