java集合框架中的比较器

时间:2014-05-17 16:47:03

标签: java collections treeset

    import java.util.*;
     class MyComp implements Comparator<String>{
        public int compare(String a ,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();
    }

}

任何人都可以解释输入的反转是如何发生的吗? 我无法理解如何比较两个角色。

1 个答案:

答案 0 :(得分:3)

您不是在比较字符,而是在比较String个字符。并且您的自定义Comparator<String>返回将第二个字符串与第一个字符串进行比较的结果,从而得到相反的顺序。请注意,比较器中的代码可以很容易地简化为:

class MyComp implements Comparator<String> {
    public int compare(String a ,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);
    }
}   

更多信息:


TreeSet<E>使用提供的Comparator<E>来评估插入元素时的顺序。让我们按照代码(你应该调试它):

ts.add("c");
//comparator will compare "c" and "c" (very silly but that's how is implemented)
//"c" will be the root of the tree
ts.add("e");
//comparator will compare "e" and "c"
//since "e" is lower than "c", "e" will be placed to the left of "c".
ts.add("b");
//comparator will compare "b" and "c"
//since "b" is greater than "c", "b" will be placed to the right of "c"
ts.add("a");
//comparator will compare "a" and "c"
//since "a" is greater than "c", "a" will be placed to the right of "c"
//but on its right is "b", so comparator will compare "a" and "b"
//since "a" is greater than "b", "a" will be placed to the right of "b"
ts.add("d");
//comparator will compare "d" and "c"
//since "d" is lower than "c", "d" will be placed to the left of "c"
//but on its left is "e", so comparator will compare "d" and "e"
//since "d" is greater than "e", "d" will be placed to the right of "e"
ts.add("g");
//comparator will compare "g" and "c"
//since "g" is lower than "c", "g" will be placed to the left of "c"
//but on its left is "e", so comparator will compare "g" and "e"
//since "g" is lower than "e", "g" will be placed to the left of "e"
ts.add("f");
//comparator will compare "f" and "c"
//since "f" is lower than "c", "f" will be placed to the left of "c"
//but on its left is "e", so comparator will compare "f" and "e"
//since "f" is lower than "e", "f" will be placed to the left of "e"
//but on its left is "g", so comparator will compare "f" and "g"
//since "f" is greater than "g", "f" will be placed to the right of "g"
//if the tree becomes unbalanced, TreeSet will be automatically balanced.