Java () ------ TreeSet

Source: Internet
Author: User
Tags addall

Like HashSet implementation based on HashMap, TreeSet is also implemented based on TreeMap. In Java enhancement () ----- TreeMap, LZ explains the TreeMap implementation mechanism in detail. If you read this blog post or learn more about TreeMap, therefore, the implementation of TreeSet is as simple as drinking water.

I. TreeSet Definition

We know that TreeMap is an ordered binary tree, so similarly, TreeSet is also an ordered one. Its function is to provide an Ordered Set. Through the source code, we know the basic AbstractSet of TreeSet to implement the NavigableSet, Cloneable, and Serializable interfaces. AbstractSet providesSetThe backbone implementation of the interface, thus minimizing the work required to implement this interface. NavigableSet is extendedSortedSetHas a navigation method that is the closest to matching items for a given search Target report, which means it supports a series of navigation methods. For example, find the most matched item with the specified target. Cloneable supports cloning and Serializable supports serialization.

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

At the same time, the following variables are defined in TreeSet.

Private transient NavigableMap <E, Object> m; // The PRESENT is constructed as the Map value and key into a key value pair private static final Object PRESENT = new Object ();

Its construction method:

// Default constructor, which sorts the public TreeSet () {this (new TreeMap <E, Object> () according to the natural order of its elements ());} // construct a new TreeSet containing the specified collection element, which is sorted in the natural order of its elements. Public TreeSet (Comparator <? Super E> comparator) {this (new TreeMap <> (comparator);} // constructs a new empty TreeSet, Which is sorted by the specified comparator. Public TreeSet (Collection <? Extends E> c) {this (); addAll (c) ;}// constructs a new TreeSet with the same ing and sorting as the specified ordered set. Public TreeSet (SortedSet <E> s) {this (s. comparator (); addAll (s);} TreeSet (NavigableMap <E, Object> m) {this. m = m ;}
Ii. Main TreeSet Methods

1,Add: add the specified element to this set (if the element does not exist in the set ).

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

2,AddAll: add all elements in the specified collection to this 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: returns the smallest element in the set that is equal to or greater than the given element. If such an element does not exist, null is returned.

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

4,Clear: removes all elements from this set.

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

5. clone: returns the superficial copy of The TreeSet instance. It is a shortest copy.

public Object clone() {        TreeSet<E> clone = null;        try {            clone = (TreeSet<E>) super.clone();        } catch (CloneNotSupportedException e) {            throw new InternalError();        }        clone.m = new TreeMap<>(m);        return clone;    }

6. comparator: return the comparator for sorting the elements in this set. If this set uses the natural sequence of its elements, null is returned.

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

7. contains: If the set contains the specified element, true is returned.

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

8. descendingIterator: return the iterator that iterates on the set element in descending order.

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

9. descendingSet: returns the reverse view of the elements contained in the set.

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

10. first: returns the first (lowest) element in the set.

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

11. floor: return the largest element in the set equal to or greater than the given element. If such element does not exist, return null.

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

12. headSet: return some views of this set. Its elements are strictly less than the toElement.

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

13. higher: returns the minimum element strictly greater than the given element in this set. If such an element does not exist, null is returned.

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

14. isEmpty: If this set does not contain any elements, true is returned.

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

15. iterator: The iterator that returns the elements in this set in ascending order.

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

16. last: returns the last (highest) element in the set.

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

17. lower: return the maximum element of the given element strictly smaller than the given element in this set. If such element does not exist, return null.

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

18. pollFirst: gets and removes the first (lowest) element. If this set is null, null is returned.

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

19. pollLast: gets and removes the last (highest) element. If this set is null, null is returned.

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

20. remove: remove the specified element from the set (if the element exists in this set ).

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

21. size: return the number of elements in the set (set capacity ).

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

22. subSet: return some views of this set.

/*** Return some views of this set. The element range is from fromElement to toElement. */Public NavigableSet <E> subSet (E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {return new TreeSet <> (m. subMap (fromElement, fromInclusive, toElement, toInclusive);}/*** returns some views of this set, whose elements are from fromElement (included) to toElement (not included ). */Public SortedSet <E> subSet (E fromElement, E toElement) {return subSet (fromElement, true, toElement, false );}

23. tailSet: return some views of this set.

/*** Return some views of this set. The element is greater than (or equal to, if the fully sive value is true) fromElement. */Public NavigableSet <E> tailSet (E fromElement, boolean random SIVE) {return new TreeSet <> (m. tailMap (fromElement, inclusive);}/*** return some views of this set. The element is greater than or equal to fromElement. */Public SortedSet <E> tailSet (E fromElement) {return tailSet (fromElement, true );}
Iii. Final

Because TreeSet is implemented based on TreeMap, if we have a certain understanding of treeMap and TreeSet is a piece of cake, we can see from the source code in TreeSet that the implementation process is very simple, almost all methods are implemented based on TreeMap.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.