Java提高篇(二八)------TreeSet


與HashSet是基於HashMap實現一樣,TreeSet同樣是基於TreeMap實現的。在《Java提高篇(二七)-----TreeMap》中LZ詳細講解了TreeMap實現機制,如果客官詳情看了這篇博文或者多TreeMap有比較詳細的了解,那么TreeSet的實現對您是喝口水那么簡單。

一、TreeSet定義

我們知道TreeMap是一個有序的二叉樹,那么同理TreeSet同樣也是一個有序的,它的作用是提供有序的Set集合。通過源碼我們知道TreeSet基礎AbstractSet,實現NavigableSet、Cloneable、Serializable接口。其中AbstractSet提供 Set 接口的骨干實現,從而最大限度地減少了實現此接口所需的工作。NavigableSet是擴展的 SortedSet,具有了為給定搜索目標報告最接近匹配項的導航方法,這就意味着它支持一系列的導航方法。比如查找與指定目標最匹配項。Cloneable支持克隆,Serializable支持序列化。

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable

同時在TreeSet中定義了如下幾個變量。

private transient NavigableMap<E,Object> m;

//PRESENT會被當做Map的value與key構建成鍵值對
private static final Object PRESENT = new Object();

其構造方法:

//默認構造方法,根據其元素的自然順序進行排序
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }
</span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)">構造一個包含指定 collection 元素的新 TreeSet,它按照其元素的自然順序進行排序。</span>
<span style="color: rgb(0,0,255)">public</span> TreeSet(Comparator&lt;? <span style="color: rgb(0,0,255)">super</span> E&gt;<span style="color: rgb(0,0,0)"> comparator) {
        </span><span style="color: rgb(0,0,255)">this</span>(<span style="color: rgb(0,0,255)">new</span> TreeMap&lt;&gt;<span style="color: rgb(0,0,0)">(comparator));
}

</span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)">構造一個新的空 TreeSet,它根據指定比較器進行排序。</span>
<span style="color: rgb(0,0,255)">public</span> TreeSet(Collection&lt;? <span style="color: rgb(0,0,255)">extends</span> E&gt;<span style="color: rgb(0,0,0)"> c) {
    </span><span style="color: rgb(0,0,255)">this</span><span style="color: rgb(0,0,0)">();
    addAll(c);
}

</span><span style="color: rgb(0,128,0)">//</span><span style="color: rgb(0,128,0)">構造一個與指定有序 set 具有相同映射關系和相同排序的新 TreeSet。</span>
<span style="color: rgb(0,0,255)">public</span> TreeSet(SortedSet&lt;E&gt;<span style="color: rgb(0,0,0)"> s) {
    </span><span style="color: rgb(0,0,255)">this</span><span style="color: rgb(0,0,0)">(s.comparator());
    addAll(s);
}

TreeSet(NavigableMap</span>&lt;E,Object&gt;<span style="color: rgb(0,0,0)"> m) {
    </span><span style="color: rgb(0,0,255)">this</span>.m =<span style="color: rgb(0,0,0)"> m;
}</span></pre>

二、TreeSet主要方法

1、add:將指定的元素添加到此 set(如果該元素尚未存在於 set 中)。

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

2、addAll:將指定 collection 中的所有元素添加到此 set 中。

public  boolean addAll(Collection<? extends E> c) {
        // Use linear-time version if applicable
        if (m.size()==0 && c.size() > 0 &&
            c instanceof SortedSet &&
            m instanceof TreeMap) {
            SortedSet<? extends E> set = (SortedSet<? extends E>) c;
            TreeMap<E,Object> map = (TreeMap<E, Object>) m;
            Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
            Comparator<? super E> mc = map.comparator();
            if (cc==mc || (cc != null && cc.equals(mc))) {
                map.addAllForTreeSet(set, PRESENT);
                return true;
            }
        }
        return super.addAll(c);
    }

3、ceiling:返回此 set 中大於等於給定元素的最小元素;如果不存在這樣的元素,則返回 null。

public E ceiling(E e) {
        return m.ceilingKey(e);
    }

4、clear:移除此 set 中的所有元素。

public void clear() {
        m.clear();
    }

5、clone:返回 TreeSet 實例的淺表副本。屬於淺拷貝。

public Object clone() {
        TreeSet<E> clone = null;
        try {
            clone = (TreeSet<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    clone.m </span>= <span style="color: rgb(0,0,255)">new</span> TreeMap&lt;&gt;<span style="color: rgb(0,0,0)">(m);
    </span><span style="color: rgb(0,0,255)">return</span><span style="color: rgb(0,0,0)"> clone;
}</span></pre>

6、comparator:返回對此 set 中的元素進行排序的比較器;如果此 set 使用其元素的自然順序,則返回 null。

public Comparator<? super E> comparator() {
        return m.comparator();
    }

7、contains:如果此 set 包含指定的元素,則返回 true。

public boolean contains(Object o) {
        return m.containsKey(o);
    }

8、descendingIterator:返回在此 set 元素上按降序進行迭代的迭代器。

public Iterator<E> descendingIterator() {
        return m.descendingKeySet().iterator();
    }

9、descendingSet:返回此 set 中所包含元素的逆序視圖。

public NavigableSet<E> descendingSet() {
        return new TreeSet<>(m.descendingMap());
    }

10、first:返回此 set 中當前第一個(最低)元素。

public E first() {
        return m.firstKey();
    }

11、floor:返回此 set 中小於等於給定元素的最大元素;如果不存在這樣的元素,則返回 null。

public E floor(E e) {
        return m.floorKey(e);
    }

12、headSet:返回此 set 的部分視圖,其元素嚴格小於 toElement。

public SortedSet<E> headSet(E toElement) {
        return headSet(toElement, false);
    }

13、higher:返回此 set 中嚴格大於給定元素的最小元素;如果不存在這樣的元素,則返回 null。

public E higher(E e) {
        return m.higherKey(e);
    }

14、isEmpty:如果此 set 不包含任何元素,則返回 true。

public boolean isEmpty() {
        return m.isEmpty();
    }

15、iterator:返回在此 set 中的元素上按升序進行迭代的迭代器。

public Iterator<E> iterator() {
        return m.navigableKeySet().iterator();
    }

16、last:返回此 set 中當前最后一個(最高)元素。

public E last() {
        return m.lastKey();
    }

17、lower:返回此 set 中嚴格小於給定元素的最大元素;如果不存在這樣的元素,則返回 null。

public E lower(E e) {
        return m.lowerKey(e);
    }

18、pollFirst:獲取並移除第一個(最低)元素;如果此 set 為空,則返回 null。

public E pollFirst() {
        Map.Entry<E,?> e = m.pollFirstEntry();
        return (e == null) ? null : e.getKey();
    }

19、pollLast:獲取並移除最后一個(最高)元素;如果此 set 為空,則返回 null。

public E pollLast() {
        Map.Entry<E,?> e = m.pollLastEntry();
        return (e == null) ? null : e.getKey();
    }

20、remove:將指定的元素從 set 中移除(如果該元素存在於此 set 中)。

public boolean remove(Object o) {
        return m.remove(o)==PRESENT;
    }

21、size:返回 set 中的元素數(set 的容量)。

public int size() {
        return m.size();
    }

22、subSet:返回此 set 的部分視圖

/**
     * 返回此 set 的部分視圖,其元素范圍從 fromElement 到 toElement。
     */
     public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
             E toElement,   boolean toInclusive) {
             return new TreeSet<>(m.subMap(fromElement, fromInclusive,
                  toElement,   toInclusive));
     }
 </span><span style="color: rgb(0,128,0)">/**</span><span style="color: rgb(0,128,0)">
  * 返回此 set 的部分視圖,其元素從 fromElement(包括)到 toElement(不包括)。
  </span><span style="color: rgb(0,128,0)">*/</span>
 <span style="color: rgb(0,0,255)">public</span> SortedSet&lt;E&gt;<span style="color: rgb(0,0,0)"> subSet(E fromElement, E toElement) {
     </span><span style="color: rgb(0,0,255)">return</span> subSet(fromElement, <span style="color: rgb(0,0,255)">true</span>, toElement, <span style="color: rgb(0,0,255)">false</span><span style="color: rgb(0,0,0)">);
 }</span></pre>

23、tailSet:返回此 set 的部分視圖

/**
     * 返回此 set 的部分視圖,其元素大於(或等於,如果 inclusive 為 true)fromElement。
     */
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
        return new TreeSet<>(m.tailMap(fromElement, inclusive));
    }
</span><span style="color: rgb(0,128,0)">/**</span><span style="color: rgb(0,128,0)">
 * 返回此 set 的部分視圖,其元素大於等於 fromElement。
 </span><span style="color: rgb(0,128,0)">*/</span>
<span style="color: rgb(0,0,255)">public</span> SortedSet&lt;E&gt;<span style="color: rgb(0,0,0)"> tailSet(E fromElement) {
    </span><span style="color: rgb(0,0,255)">return</span> tailSet(fromElement, <span style="color: rgb(0,0,255)">true</span><span style="color: rgb(0,0,0)">);
}</span></pre>

三、最后

由於TreeSet是基於TreeMap實現的,所以如果我們對treeMap有了一定的了解,對TreeSet那是小菜一碟,我們從TreeSet中的源碼可以看出,其實現過程非常簡單,幾乎所有的方法實現全部都是基於TreeMap的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM