A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© lijiy09 中级黑马   /  2016-3-20 22:21  /  537 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check
            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
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            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;
    }
这里Comparable和Comparator接口,已经被搞晕了,求大神详解该类方法?

2 个回复

倒序浏览
要么让子类去实现Comparable接口去比较,,要么用匿名内部类重写Comparator中 conpare方法去比较
回复 使用道具 举报
这哪是Set啊,明明是Map的源码嘛
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马