文章介绍:
在一部分教程中,会说到TreeSet和TreeMap用无参构造器创建后输出的对象排序是无序的,但经过我验证实操后发现,并不是无序的,而是有序的;
验证代码:
TreeMap treeMap = new TreeMap();
treeMap.put("Jack", "杰克");
treeMap.put("Tom", "汤姆");
treeMap.put("John", "约翰");
treeMap.put("Mary", "玛丽");
treeMap.put("Apple", "苹果");
treeMap.put("Lory", "罗瑞");
treeMap.put("Bcd", "碧玺");
treeMap.put("wtf", "WTF");
treeMap.put("1", "WTF");
treeMap.put("3", "WTF");
treeMap.put("2", "WTF");
treeMap.put("5", "WTF");
treeMap.put("7", "WTF");
System.out.println("无参构造器:" + treeMap);
TreeMap newTreeMap = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
String s1 = o1 + " ";
String s2 = o2 + " ";
return s1.compareTo(s2);
}
});
newTreeMap.put("Jack", "杰克");
newTreeMap.put("Tom", "汤姆");
newTreeMap.put("John", "约翰");
newTreeMap.put("Mary", "玛丽");
newTreeMap.put("Apple", "苹果");
newTreeMap.put("Lory", "罗瑞");
newTreeMap.put("Bcd", "碧玺");
newTreeMap.put("wtf", "WTF");
newTreeMap.put(1, "WTF");
newTreeMap.put(3, "WTF");
newTreeMap.put(2, "WTF");
newTreeMap.put(5, "WTF");
newTreeMap.put(7, "WTF");
System.out.println("有参构造器:" + newTreeMap);
这里可以发现无参构造器创建的对象和我自定义的比较器排序是相同的。
追入源码查看
JDK源码:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
追入后是可以发现底层是存在比较操作的,而KEY为String时默认的比较器就是String下的compareTo方法,当我们把传入数据放入int类型或者char类型,就更可以验证这个观点
注意!!!
这里会是String的compareTo方法其实是因为JDK在底层中会调用key自带的比较器,会存在动态绑定
TreeMap treeMap = new TreeMap();
treeMap.put("Jack", "杰克");
treeMap.put("Tom", "汤姆");
treeMap.put("John", "约翰");
treeMap.put("Mary", "玛丽");
treeMap.put("Apple", "苹果");
treeMap.put("Lory", "罗瑞");
treeMap.put("Bcd", "碧玺");
treeMap.put("wtf", "WTF");
treeMap.put(1, "WTF");
treeMap.put(3, "WTF");
treeMap.put(2, "WTF");
treeMap.put(5, "WTF");
treeMap.put(7, "WTF");
System.out.println("无参构造器:" + treeMap);
这里报错是信息是int型无法与String型比较,就可以说明用无参构造器创造对象时是存在默认构造器的。
若需要int型和String型比较,就需要自定义比较器,就是我在上面写的有参构造器,一般推荐用匿名内部类的方式来写。