Just out of curiosity, i wanted t know how TreeSet maintains order. Of course by comparing new element to add to previous elements either by element object's comparator or any custom comparator. But there could be better approach than comparing all. Lets see some code:
TreeSet<String> tset= new TreeSet<>(new comparator<String>());
tset.add("america");
tset.add("britain");
tset.add("india");
tset.add("checksolvakia");
tset.add("china");
tset.add("sri_lanka");
tset.add("zimbabwe");
for(String str:tset){
System.out.println(str);
}
In above code new comparator<String>() is just an custom comparator that do normal string comparisons.
The output drom above code is:
i have been called times:1
values America America
i have been called times:2
values Britain America
i have been called times:3
values india America
i have been called times:4
values india Britain
i have been called times:5
values checksolvakia Britain
i have been called times:6
values checksolvakia india
i have been called times:7
values china Britain
i have been called times:8
values china india
i have been called times:9
values china checksolvakia
i have been called times:10
values sri_lanka Britain
i have been called times:11
values sri_lanka china
i have been called times:12
values sri_lanka india
i have been called times:13
values zimbabwe Britain
i have been called times:14
values zimbabwe china
i have been called times:15
values zimbabwe india
i have been called times:16
values zimbabwe sri_lanka
america
britain
checksolvakia
china
india
sri_lanka
zimbabwe
Now the questions:
1. why america was compared to america??
2.why everyone else was not compared to america?? is it set as Root??
even if its is set as root why no comparison to root.
3. there could be less comparisons in say zimbabwe could be compared to something not Britain(ie not from very start).

TreeMapcompares an object to itself if it is the first element in the map, to verify that the object is comparable with the specified comparator -- in previous JDK versions, there were some unpleasant bugs withnullhere, for example, or with raw types causing elements of the wrong type to be allowed into the map.