集合框架_TreeSet保证元素排序的源码解析

interface Collection{...}
interface Set extends Collection{...}

interface NavigableMap{}

class TreeMap implements NavigableMap{
	public V put(K key, V value) {
        Entry t = root;
        if (t == null) {
	    // TBD:
	    // 5045147: (coll) Adding null to an empty TreeSet should
	    // throw NullPointerException
	    //
	    // compare(key, key); // type check
            root = new Entry(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry parent;
        // split comparator and comparable paths
        Comparator 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 k = (Comparable) 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 e = new Entry(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }
}

class TreeSet implements Set{
	private transient NavigableMap m;
	
	public TreeSet(){
		this(new TreeMap());
	}

	public boolean add(E e) {
		return m.put(e, PRESENT)==null;
    }
}

真正比较的是依赖于元素的compareTo()方法,而这个方法是定义在Comparable里面的
所以,你想要重写该方法,就必须是先Comparable接口。这个接口表示的就是自然排序。

你可能感兴趣的:(Java,Set,TreeSet,Comparable)