gpt4 book ai didi

java - java集合框架中的比较器

转载 作者:行者123 更新时间:2023-12-01 22:58:28 25 4
gpt4 key购买 nike

    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();
}

}

谁能解释一下输入的相反是如何发生的?我无法理解如何比较两个角色。

最佳答案

您不是在比较字符,而是在比较单一长度 String s。和您的定制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.

关于java - java集合框架中的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23713816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com