comparators in java collection framework -


    import java.util.*;      class mycomp implements comparator<string>{         public int compare(string ,string b){             system.out.println(a+"  "+b);             string astr,bstr;             astr=a;             bstr=b;              int g = bstr.compareto(astr);             return g;         }     }     public class compdemo {     public static void main(string[] args) {         treeset<string> ts =new treeset<string>(new mycomp());         ts.add("c");         ts.add("e");         ts.add("b");         ts.add("a");         ts.add("d");         ts.add("g");         ts.add("f");         for(string element:ts)             system.out.println(element+" ");         system.out.println();     }  } 

can explain how reverse of input happening ? not able understand how 2 characters being compared.

you're not comparing characters one-length strings. , custom comparator<string> returns result of comparing second string against first, getting reverse order. note code in comparator can reduced to:

class mycomp implements comparator<string> {     public int compare(string ,string b) {         /*         system.out.println(a+"  "+b);         string astr,bstr;         astr=a;         bstr=b;          int g = bstr.compareto(astr);         return g;         */         return b.compareto(a);     } }    

more info:


treeset<e> uses provided comparator<e> evaluate order of elements when inserting them. let's follow code (you should debug it):

ts.add("c"); //comparator compare "c" , "c" (very silly that's how implemented) //"c" root of tree ts.add("e"); //comparator compare "e" , "c" //since "e" lower "c", "e" placed left of "c". ts.add("b"); //comparator compare "b" , "c" //since "b" greater "c", "b" placed right of "c" ts.add("a"); //comparator compare "a" , "c" //since "a" greater "c", "a" placed right of "c" //but on right "b", comparator compare "a" , "b" //since "a" greater "b", "a" placed right of "b" ts.add("d"); //comparator compare "d" , "c" //since "d" lower "c", "d" placed left of "c" //but on left "e", comparator compare "d" , "e" //since "d" greater "e", "d" placed right of "e" ts.add("g"); //comparator compare "g" , "c" //since "g" lower "c", "g" placed left of "c" //but on left "e", comparator compare "g" , "e" //since "g" lower "e", "g" placed left of "e" ts.add("f"); //comparator compare "f" , "c" //since "f" lower "c", "f" placed left of "c" //but on left "e", comparator compare "f" , "e" //since "f" lower "e", "f" placed left of "e" //but on left "g", comparator compare "f" , "g" //since "f" greater "g", "f" placed right of "g" //if tree becomes unbalanced, treeset automatically balanced. 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -