首页 > Java TreeMap的put()方法中利用泛型创建接口对象?

Java TreeMap的put()方法中利用泛型创建接口对象?

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都是通过传递的子类引用,而且还有一些具体的关于TreeMap和TreeSet的分析在一下文章中:
[Java 集合类 TreeSet、TreeMap] http://www.cnblogs.com/scyitgz/p/5103690.html

【热门文章】
【热门文章】