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>();
map.put("a","ant");
map.put("d","dog");
map.put("h","horse");

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

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

map.put("b", "bat");
submap.put("f","fish");

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".

Recommended Answers

All 4 Replies

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

Thankss James, Got it .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.