import java.util.Comparator;
import java.util.TreeSet;
/**
* @ClassName TreeSet_
* @Description
* @Author 小黄debug
* @Date 2022/3/14 0:17
* @Version 1.0
**/
public class TreeSet_ {
public static void main(String[] args) {
//解读
//1.当我们使用无参构造器,创建Tree时,仍然是无序的
//2.老师希望添加元素,按照字符串大小来排序
//3.使用TreeSet提供的一个构造器,可以传入一个比较器(匿名内部类)
// 并指定排序规则
//简单看看源码
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//下面调用String的compareTo方法进行字符串大小比较
//如果要求加入的元素,按元素的长度大小排序
//return ((String)o2).compareTo((String)o1);
return ((String)o2).length() - ((String)o1).length();
}
});
//TreeSet treeSet = new TreeSet();
//添加数据
treeSet.add("jack");
treeSet.add("tom");
treeSet.add("a");
treeSet.add("sp");
treeSet.add("abc"); //此处是否能加进行,根据排序规则决定,由于abc和tom都是三个字符,会被认为是相同元素
System.out.println("treeSet="+treeSet);
/*
1.构造器把传入的比较器对象,赋给了TreeSet底层的TreeMap的属性this.comparator
public TreeMap(Comparator<? super K> comparator){
this.comparator = comparator;
}
2.在调用treeSet.add("tom",在底层会执行到
if(cpr != null){ //cpr就是我们匿名内部类(对象)
do{
parent = t;
//动态绑定到我们的匿名内部(对象)compare
com = cpr.comare(key,t.key);
if(cmp < 0)
t = t.left;
else if(cmp > 0)
t = t.right
slse{ //如果同等,就返回0,这个Key就没有加入
return t.setValue(value
}
while(t != null);
}
}
*/
}
}
Java基础 TreeSet
最新推荐文章于 2024-05-15 17:09:12 发布