TreeMap源码阅读

基本结构

    private final Comparator<? super K> comparator;

    private transient Entry<K,V> root;
    //根节点   
    /**
     * The number of entries in the tree
     */
    private transient int size = 0;
    //元素个数

    /**
     * The number of structural modifications to the tree.
     */
    private transient int modCount = 0;
    //树结构修改数

//下面是根节点的结构,红黑树
    static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        /**
         * Make a new cell with given key, value, and parent, and with
         * {@code null} child links, and BLACK color.
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

    }

put

 public V put(K key, V value) {
        Entry<K,V> t = root;//根节点
        if (t == null) {//如果entry当中还没有数据,初始化
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;//元素个数1
            modCount++;//树结构修改+1
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;//这个值可以在TreeMap构造函数出初始化
        if (cpr != null) {//接下来就是通过判断是否在TreeMap初始化时初始化了Comparator,如果是,来left和right,但=0时,直接替换掉
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {//如果没有初始化Comparator,就从比较的object key中取出Comparable,也就是key中impements Comparable接口
            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);//找到后,新建节点,根据cmp结果放在左边右边
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }

get

public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }
final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)//这边是treeMap实现了Comparator接口
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;
        while (p != null) {//这边是,没实现,但是key这个object中实现了Comparable接口
            int cmp = k.compareTo(p.key);
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
        return null;
    }
final Entry<K,V> getEntryUsingComparator(Object key) {\\这边是treeMap实现了Comparator接口
        @SuppressWarnings("unchecked")
            K k = (K) key;
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            Entry<K,V> p = root;
            while (p != null) {
                int cmp = cpr.compare(k, p.key);
                if (cmp < 0)
                    p = p.left;
                else if (cmp > 0)
                    p = p.right;
                else
                    return p;
            }
        }
        return null;
    }
    \\具体查询就树遍历一样,用存放的规则再来寻找

结论
首先,如果想要存入进TreeMap中,首先有前提,TreeMap初始化的时候要实现Comparator接口,并重写compare方法 *或者是***TreeMap存入的key这个object实现了Comparable接口,并重写了compareTo方法

下面实现两个方法
1.object key中实现Comparable接口

public class Person implements Comparable<Person> {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Person o) {
        if(this.name.equals(o.getName())){//这个地方,我将相同的信息,返回1,不同返回-1,当然这不符合逻辑,我只是尝试一下
            return 1;
        }else{
            return -1;
        }
    }
}


import java.util.*;

public class TreeMapDemo {
    public static void main(String[] args){
        TreeMap<Person,Integer> treeMap = new TreeMap<Person, Integer>();
        treeMap.put(new Person("husky"),1);
        treeMap.put(new Person("husky"),2);
        treeMap.put(new Person("husky"),3);


          Set<Map.Entry<Person,Integer>> entry = treeMap.entrySet();
          for(Map.Entry<Person,Integer> e:entry){
              System.out.println(e.getKey().getName()+"  "+e.getValue());
          }

    }
}
//输出结果
/**
husky  1
husky  2
husky  3
*/

2.TreeMap初始化是,初始化了Comparator接口

public class Person  {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

import java.util.*;

public class TreeMapDemo {
    public static void main(String[] args){
        TreeMap<Person,Integer> treeMap = new TreeMap<Person, Integer>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if (o1.getName().equals(o2)){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        treeMap.put(new Person("husky"),1);
        treeMap.put(new Person("husky"),2);
        treeMap.put(new Person("husky"),3);


          Set<Map.Entry<Person,Integer>> entry = treeMap.entrySet();
          for(Map.Entry<Person,Integer> e:entry){
              System.out.println(e.getKey().getName()+"  "+e.getValue());
          }
    }
}

/**
husky  3
husky  2
husky  1
*/

参考博客java集合(6):TreeMap源码分析(jdk1.8)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值