Java Collection source code analysis (6) TreeSet & lt; E & gt;, javatreeset

Source: Internet
Author: User
Tags addall

Java Collection source code analysis (6) TreeSet <E>, javatreeset
Introduction to TreeSet

TreeSet is an ordered Set. It provides an ordered Set. It inherits from the AbstractSet abstract class and implements the NavigableSet <E>, Cloneable, and java. io. Serializable interfaces.
TreeSet is inherited from AbstractSet. Therefore, it is a Set with the Set attributes and methods.
TreeSet implements the NavigableSet interface, which means it supports a series of navigation methods. For example, find the most matched item with the specified target.
TreeSet implements the Cloneable interface, which means it can be cloned.
TreeSet implements the java. io. Serializable interface, meaning it supports serialization.

TreeSet is implemented based on TreeMap. The elements in the TreeSet support two sorting methods: Natural sorting or sorting based on the Comparator provided when the TreeSet is created. This depends on the constructor used.
TreeSet provides guaranteed log (n) time overhead for basic operations (add, remove, and contains.
In addition, TreeSet is not synchronous. The iterator returned by its iterator method is fail-fast.

TreeSet Constructor
// Default constructor. With this constructor, elements in the TreeSet are arranged in natural order. TreeSet () // The created TreeSet contains collectionTreeSet (Collection <? Extends E> collection) // specifies the TreeSet Comparator TreeSet (Comparator <? Super E> comparator) // The created TreeSet contains setTreeSet (SortedSet <E> set)
TreeSet API
boolean                   add(E object)boolean                   addAll(Collection<? extends E> collection)void                      clear()Object                    clone()boolean                   contains(Object object)E                         first()boolean                   isEmpty()E                         last()E                         pollFirst()E                         pollLast()E                         lower(E e)E                         floor(E e)E                         ceiling(E e)E                         higher(E e)boolean                   remove(Object object)int                       size()Comparator<? super E>     comparator()Iterator<E>               iterator()Iterator<E>               descendingIterator()SortedSet<E>              headSet(E end)NavigableSet<E>           descendingSet()NavigableSet<E>           headSet(E end, boolean endInclusive)SortedSet<E>              subSet(E start, E end)NavigableSet<E>           subSet(E start, boolean startInclusive, E end, boolean endInclusive)NavigableSet<E>           tailSet(E start, boolean startInclusive)SortedSet<E>              tailSet(E start)
Note:

(01) TreeSet is an ordered Set. Therefore, methods such as add, remove, and get are supported.
(02) Like NavigableSet, TreeSet navigation methods can be roughly divided into two categories. For one type, the navigation method of element items is provided to return an element. For the other type, the navigation method of the set is provided, returns a set.
Lower, floor, ceiling, and higher return the elements smaller than, less than or equal to, greater than or equal to, and greater than the given element. If such elements do not exist, null is returned.

TreeSet source code analysis

For TreeSet, it is implemented based on TreeMap, and TreeSet uses TreeMap to store all elements at the underlying layer. Therefore, the implementation of TreeSet is relatively simple, and operations on TreeSet are related, basically, it is done by directly calling the underlying TreeMap method,
The source code of TreeSet is as follows:

 

/** @ (#) TreeSet. java1.37 06/05/10 ** Copyright 2006 Sun Microsystems, Inc. all rights reserved. * sun proprietary/CONFIDENTIAL. use is subject to license terms. */package java. util;/*** @ param <E> the type of elements maintained by this set *** @ author Josh Bloch * @ version 1.37, 05/10/06 * @ see Collection * @ see Set * @ see HashSet * @ see Comparable * @ see Comparator * @ see TreeMap * @ since 1.2 */Public class TreeSet <E> extends AbstractSet <E> implements NavigableSet <E>, Cloneable, java. io. serializable {/*** NavigableMap Object */private transient NavigableMap <E, Object> m; // TreeSet is implemented through TreeMap, and // PRESENT is the value in the key-value pair. Private static final Object PRESENT = new Object ();/*** assign TreeMap to "NavigableMap Object m" */TreeSet (NavigableMap <E, Object> m) {this. m = m;}/*** a constructor without parameters. Create an empty TreeMap */public TreeSet () {this (new TreeMap <E, Object> () ;}/ *** constructor with comparator. */Public TreeSet (Comparator <? Super E> comparator) {this (new TreeMap <E, Object> (comparator);}/*** create a TreeSet, add all the elements in set c to TreeSet */public TreeSet (Collection <? Extends E> c) {this (); addAll (c) ;}/ *** create a TreeSet, add all elements in s to TreeSet */public TreeSet (SortedSet <E> s) {this (s. comparator (); addAll (s) ;}/ *** returns the sorted iterator of the TreeSet. * Because TreeSet is implemented by TreeMap, the corresponding Iterator */public iterator <E> Iterator () {return m is actually returned here. navigableKeySet (). iterator ();}/*** returns the iterator in the descending order of the TreeSet. * Because TreeSet is implemented by TreeMap, the corresponding Iterator */public Iterator <E> descendingIterator () {return m is actually returned here. descendingKeySet (). iterator ();}/*** return NavigableSet <E> TreeSet */public NavigableSet <E> descendingSet () {return new TreeSet (m. descendingMap ();}/*** returned size */public int size () {return m. size ();}/*** is empty */public boolean isEmpty () {return m. isEmpty ();}/*** whether to include o */public boolean Contains (Object o) {return m. containsKey (o);}/*** add Element e */public boolean add (E e) {return m. put (e, PRESENT) = null;}/*** Delete element o */public boolean remove (Object o) {return m. remove (o) = PRESENT;}/*** clear set */public void clear () {m. clear ();}/*** add all the elements in set c to TreeSet */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);}/*** returns the sub-Set, which is actually implemented through subMap () of TreeMap. */Public NavigableSet <E> subSet (E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {return new TreeSet <E> (m. subMap (fromElement, fromInclusive, toElement, toInclusive);}/*** returns the Set header, range: From header to toElement. * Indicates whether the toElement flag is contained. */public NavigableSet <E> headSet (E toElement, boolean strongly SIVE) {return new TreeSet <E> (m. headMap (toElement, inclusive);}/*** returns the end of the Set, range: From fromElement to the end. * Implicit sive indicates whether fromElement is included */public NavigableSet <E> tailSet (E fromElement, boolean implicit SIVE) {return new TreeSet <E> (m. tailMap (fromElement, inclusive);}/*** returns the sub-Set. The range is from fromElement (included) to toElement (not included ). */Public SortedSet <E> subSet (E fromElement, E toElement) {return subSet (fromElement, true, toElement, false);}/*** return the Set header, range: From header to toElement (not included ). */Public SortedSet <E> headSet (E toElement) {return headSet (toElement, false);}/*** return the end of the Set, range: from fromElement to the end (not included ). */Public SortedSet <E> tailSet (E fromElement) {return tailSet (fromElement, true);} // return the Set Comparator public Comparator <? Super E> comparator () {return m. comparator ();}/*** returns the first element of Set */public E first () {return m. firstKey ();}/*** returns the last element of Set */public E last () {return m. lastKey ();} // NavigableSet API methods/*** returns the largest element in the Set smaller than e */public E lower (E e) {return m. lowerKey (e);}/*** returns the largest element in the Set smaller than/equal to e */public E floor (E e) {return m. floorKey (e);}/*** returns the smallest element in the Set that is greater than/equal to e */public E ceiling (E e) {retu Rn m. ceilingKey (e);}/*** returns the smallest element in Set greater than e */public E higher (E) {return m. higherKey (e);}/*** get the first element and delete it from TreeMap. */Public E pollFirst () {Map. Entry <E,?> E = m. pollFirstEntry (); return (e = null )? Null: e. getKey ();}/*** get the last element and delete it from TreeMap. */Public E pollLast () {Map. Entry <E,?> E = m. pollLastEntry (); return (e = null )? Null: e. getKey ();}/*** clone a TreeSet and return the Object */public Object clone () {TreeSet <E> clone = null; try {clone = (TreeSet <E>) super. clone ();} catch (CloneNotSupportedException e) {throw new InternalError ();} clone. m = new TreeMap <E, Object> (m); return clone;}/*** java. io. the Serializable write function ** writes the "comparator, capacity, and all element values" of the TreeSet to the output stream */private void writeObject (java. io. objectOutputStream s) throws ja Va. io. IOException {// Write out any hidden stuffs. defaultWriteObject (); // write the comparator s. writeObject (m. comparator (); // write capacity s. writeInt (m. size (); // write "every element in TreeSet" for (Iterator I = m. keySet (). iterator (); I. hasNext ();) s. writeObject (I. next ();}/*** java. io. serializable READ function: Read the data according to the write mode * First read the "comparator, capacity, and all element values" of the TreeSet */private void readObject (java. io. objectInputStream s) throws java. io. IOException, ClassNotFoundException {// Read in any hidden stuffs. defaultReadObject (); // Read the "Comparator" Comparator <? Super E> c = (Comparator <? Super E>) s. readObject (); // Create backing TreeMapTreeMap <E, Object> tm; if (c = null) tm = new TreeMap <E, Object> (); else tm = new TreeMap <E, Object> (c); m = tm; // read the "capacity" int size = s of the TreeSet from the input stream. readInt (); // read the "all elements" tm of the TreeSet from the input stream. readTreeSet (size, s, PRESENT);} // The sequence version of The TreeSet private static final long serialVersionUID =-2479143000061671589L ;}

 

Summary:

(01) TreeSet is actually implemented by TreeMap. When we construct a TreeSet, if a constructor without parameters is used, the TreeSet uses a natural comparator. If you need a custom comparator, you need to use a parameter with a comparator.
(02) TreeSet is non-thread-safe.
(03) Implement java. io. Serializable using TreeSet. When writing data to the output stream, the following elements are written in sequence: comparator, capacity, and all elements. when reading the input stream, read the data in sequence.

 

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.