Java Collection Learning (17) TreeSet Detailed introduction (source analysis) and usage examples

Source: Internet
Author: User
Tags addall constructor empty header int size object object range set set


In this chapter, we learn about TreeSet.
We first have a general understanding of TreeSet, and then learn its source, and finally through the example to learn to use TreeSet.



The 1th part TreeSet introduction



TreeSet Introduction



TreeSet is an ordered set of functions that provide an ordered set set. It inherits from the Abstractset abstract class, implements the Navigableset<e>, cloneable, java.io.Serializable interface.
TreeSet inherits from Abstractset, so it is a set set with properties and methods of set.
TreeSet implements the Navigableset interface, which means it supports a range of navigation methods. For example, find the most matches with the specified target.
TreeSet implements the Cloneable interface, meaning it can be cloned.
TreeSet implements the Java.io.Serializable interface, which means it supports serialization.



TreeSet is implemented based on TreeMap. The elements in TreeSet support 2 sort methods: natural sorting or sorting according to the Comparator provided when the TreeSet is created. This depends on the construction method that is used.
TreeSet provides guaranteed log (n) time overhead for basic operations (add, remove, and contains).
In addition, TreeSet is not synchronized. Its iterator method returns an iterator that is fail-fast.



The inheritance relationship of TreeSet


Java.lang.Object
        java.util.abstractcollection<e>
              java.util.abstractset<e>
                    Java.util.treeset<e> public
     
class Treeset<e> extends abstractset<e>        
    implements Navigableset<e>, cloneable, java.io.serializable{}


The relationship between TreeSet and collection is as follows:






Constructor for TreeSet


The default constructor. Using this constructor, the elements in the TreeSet are arranged in a natural order.
TreeSet ()
     
///created TreeSet contains Collection
TreeSet (collection<? extends e> Collection)
     
// Specifies that the comparer for TreeSet
TreeSet (comparator< super e> Comparator)
     
//Created TreeSet contains set
TreeSet (sortedset <E> set)


API for TreeSet


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)


Description



TreeSet is an ordered set set and therefore supports add, remove, and get methods.
(02) As with Navigableset, TreeSet navigation methods can be roughly divided into two categories, a class of time to provide a navigation method of element items, return an element, another class when providing a collection of navigation methods, return a collection.
Lower, floor, ceiling, and higher return the elements less than, less than, equal to, greater than or equal to the given element, or null if no such element exists.



2nd part TreeSet Source Analysis



To get a better idea of the TreeSet principle, the following is an analysis of the TreeSet source code.


package java.util;
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,
//Present is the value in the key value pair.
private static final Object PRESENT = new Object();
//Constructor without parameters. Create an empty treemap
public TreeSet() {
this(new TreeMap<E,Object>());
}
//Assign treemap to navigablemap object m
TreeSet(NavigableMap<E,Object> m) {
This.m = m;
}
//Constructor with comparator.
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<E,Object>(comparator));
}
//Create a TreeSet and add all the elements in collection C to the TreeSet
public TreeSet(Collection<? extends E> c) {
This ();
//Add all elements in set C to TreeSet
AddAll (c);
}
//Create a TreeSet and add all elements in s to the TreeSet
public TreeSet(SortedSet<E> s) {
this(s.comparator());
AddAll (s);
}
//Returns the sequential iterator of the TreeSet.
//Because treemap is implemented in TreeSet, the iterator corresponding to the "keyset" of treemap is actually returned here
public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}
//Returns the iterator of TreeSet in reverse order.
//Because treemap is implemented in TreeSet, the iterator corresponding to the "keyset" of treemap is actually returned here
public Iterator<E> descendingIterator() {
return m.descendingKeySet().iterator();
}
//Returns the size of the TreeSet
public int size() {
return m.size();
}
//Return whether TreeSet is empty
public boolean isEmpty() {
return m.isEmpty();
}
//Return whether TreeSet contains objects
public boolean contains(Object o) {
return m.containsKey(o);
}
//Add e to TreeSet
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
//Delete object o in TreeSet
public boolean remove(Object o) {
return m.remove(o)==PRESENT;
}
//Empty TreeSet
public void clear() {
M.clear ();
}
//Add all elements of set C to the TreeSet
public  boolean addAll(Collection<? extends E> c) {
// Use linear-time version if applicable
if (m.size()==0 &amp;&amp; c.size() > 0 &amp;&amp;
c instanceof SortedSet &amp;&amp;
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 &amp;&amp; cc.equals(mc))) {
map.addAllForTreeSet(set, PRESENT);
Return true;
}
}
return super.addAll(c);
}
//Return the subset, which is actually implemented through the 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 header of the set, from the header to the toelement.
//Include is the flag of whether to include toelement
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new TreeSet<E>(m.headMap(toElement, inclusive));
}
//Returns the tail of the set, from fromelement to the end.
//Include is the flag of whether to include fromelement
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<E>(m.tailMap(fromElement, inclusive));
}
//Returns the subset. The range is: from fromelement (included) to toelement (excluded).
public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
//Returns the header of the set, from the header to the toelement (not included).
public SortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
//Returns the tail of the set, from fromelement to the end (not included).
public SortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
//Returns the comparator of the set
public Comparator<? super E> comparator() {
return m.comparator();
}
//Returns the first element of a set
public E first() {
return m.firstKey();
}
//Returns the last element of the set
public E first() {
public E last() {
return m.lastKey();
}
//Returns the largest element in the set less than e
public E lower(E e) {
return m.lowerKey(e);
}
//Returns the maximum element in the set less than or equal to e
public E floor(E e) {
return m.floorKey(e);
}
//Returns the smallest element in the set greater than / equal to e
public E ceiling(E e) {
return m.ceilingKey(e);
}
//Returns the minimum element greater than E in the set
public E higher(E e) {
return m.higherKey(e);
}
//Gets the first element and removes it from the treemap.
public E pollFirst() {
Map.Entry<E,?> e = m.pollFirstEntry();
return (e == null)? null : e.getKey();
}
//Gets the last element and removes it from the treemap.
public E pollLast() {
Map.Entry<E,?> e = m.pollLastEntry();
return (e == null)? null : e.getKey();
}
//Clone a TreeSet and return the object object 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;
}
//Write function of java.io.serializable
//Write TreeSet's comparator, capacity, all element values to the output stream
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
//Write 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());
}
//Read function of java.io.serializable: read according to write mode
//First read out "comparator, capacity and all element values" of TreeSet
private void readObject(java.io.ObjectInputStream s)
Throws Java


Summarize:





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.