package com.model.map.treemap;
import java.util.Comparator;
import java.util.TreeMap;
/**
* @Description:测试类
* @Author: 张紫韩
* @Crete 2021/6/15 21:47
*/
public class TreeMapDemo01 {
public static void main(String[] args) {
TreeMap<Object, Object> treeMap = new TreeMap<>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
// return ((String)o1).compareTo((String)o2); //按照字符串的AscLL值进行排序
return ((String)o1).length()-((String)o2).length(); //按照字符串的长度进行排序
}
});
treeMap.put("a","b");
treeMap.put("b","b");
treeMap.put("c","b");
treeMap.put("d","b");
treeMap.put("e","b");
treeMap.put("f","f");
System.out.println(treeMap);
}
/**
* 默认是无序的
* 实现排序:利用的树进行排序
* 需要实现 public TreeMap(Comparator<? super K> comparator) 构造方法:创建一个匿名内部
*
*1.执行new TreeMap(Comparator<? super K> comparator):
* public TreeMap(Comparator<? super K> comparator) {
* this.comparator = comparator;
* //将匿名内部类赋值给 TreeMap的comparator属性
* }
*2.执行 put():
* //第一个元素不会进行比较
* //当加入第二个元素是才会进行比较
*
* public V put(K key, V value) {
* Entry<K,V> t = root;
* //第一次添加root时null会进入
* if (t == null) {
//也会调用匿名内部类,但是比较结果对结果并不产生影响
* compare(key, key); // type (and possibly null) check
* //将这个节点赋值给root
* root = new Entry<>(key, value, null);
* size = 1;
* modCount++;
* return null;
* }
* int cmp;
* Entry<K,V> parent;
* // split comparator and comparable paths
* Comparator<? super K> cpr = comparator;
//循环比较,节点元素,先和第一个元素作比较,如果比第一个元素大就和第一个节点的右节点进行比较,反之则会和几点的左节点进行比较,知道找到
* if (cpr != null) {
* do {//遍历节点
* parent = t;
* //动态绑定我们的匿名内部类方法
* cmp = cpr.compare(key, t.key);
* if (cmp < 0)
* t = t.left;
* else if (cmp > 0)
* t = t.right;
* else //如果遍历过程中准备加入的元素和已经有的一样,就会返回就不再添加了,而只是进行value的替换
* return t.setValue(value);
* } while (t != null);
* }
* else {
* if (key == null)
* throw new NullPointerException();
* @SuppressWarnings("unchecked")
* Comparable<? super K> k = (Comparable<? super K>) key;
* do {
* parent = t;
* cmp = k.compareTo(t.key);
* if (cmp < 0)
* t = t.left;
* else if (cmp > 0)
* t = t.right;
* else
* return t.setValue(value);
* } while (t != null);
* }
//将节点放在最后一个比较节点的左侧或者右侧
* Entry<K,V> e = new Entry<>(key, value, parent);
* if (cmp < 0)
* parent.left = e;
* else
* parent.right = e;
* fixAfterInsertion(e);
* size++;
* modCount++;
* return null;
* }
*
*
*
* */
}