Thinking logic of computer programs (44), thinking 44
Section 41 introduces HashSet. we mentioned that HashSet has an important limitation and there is no specific sequence between elements. We also mentioned that the Set interface has another important implementation class TreeSet, it is ordered. Like the relationship between HashSet and HashMap, TreeSet is based on TreeMap. In the previous section, we introduced TreeMap. In this section, we will discuss TreeSet in detail.
Next, let's first look at the TreeSet usage, then look at the implementation principle, and finally summarize and analyze the features of TreeSet.
Basic usage
Constructor
The basic construction methods of TreeSet include:
public TreeSet()public TreeSet(Comparator<? super E> comparator)
The default constructor assumes that the element implements the Comparable interface, and the second uses the passed-in comparator. The element is not required to implement Comparable.
Basic example
TreeSet is often used as a Set, but it only requires iterative output, as shown in the following code:
Set<String> words = new TreeSet<String>();words.addAll(Arrays.asList(new String[]{ "tree", "map", "hash", "map", }));for(String w : words){ System.out.print(w+" ");}
Output:
hash map tree
TreeSet implements two points: weight and order.
If you want different sorting, you can pass a Comparator, as shown below:
Set<String> words = new TreeSet<String>(new Comparator<String>(){ @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); }});words.addAll(Arrays.asList(new String[]{ "tree", "map", "hash", "Map", }));System.out.println(words);
Compare by case-insensitive. The output is:
[hash, map, tree]
It should be noted that Set is for weight sorting, and the weight sorting is based on the comparison result. If the result is 0, it is regarded as the same. Although "map" and "Map" are different, the comparison result is 0, so only the first element is retained.
The above is the basic usage of TreeSet, which is easy to use. However, due to the Order, TreeSet also implements the NavigableSet and SortedSet interfaces, and NavigableSet extends SortedSet. In addition, TreeSet has several construction methods. Let's take a look.
Advanced usage
SortedSet Interface
The SortedSet interface is similar to the SortedMap interface, which is defined:
public interface SortedSet<E> extends Set<E> { Comparator<? super E> comparator(); SortedSet<E> subSet(E fromElement, E toElement); SortedSet<E> headSet(E toElement); SortedSet<E> tailSet(E fromElement); E first(); E last();}
First () returns the first element. last () returns the last element. headSet/tailSet/subSet returns a view, including elements with a certain value range in the original Set. The difference lies in the range:
- HeadSet: Strictly less than all elements of toElement
- TailSet: All elements greater than or equal to fromElement
- SubSet: All elements greater than or equal to fromElement and less than toElement
Similar to the previously introduced view concept, operations on the returned view directly affect the original Set.
Comparator () returns the comparator used. If there is no custom comparator, the return value is null.
Let's take a look at a simple sample code to enhance the intuitive feeling and output the following annotations:
SortedSet <String> set = new TreeSet <String> (); set. addAll (Arrays. asList (new String [] {"c", "a", "B", "d", "f"}); System. out. println (set. first (); // aSystem. out. println (set. last (); // fSystem. out. println (set. headSet ("B"); // [a] System. out. println (set. tailSet ("d"); // [d, f] System. out. println (set. subSet ("B", "e"); // [B, c, d] set. subSet ("B", "e "). clear (); // System will be deleted from the original set. out. println (set); // [a, f]
NavigableSet Interface
Similar to NavigableMap, The NavigableSet interface extends SortedSet and mainly adds methods for finding neighboring elements, such:
E floor (E e); // returns e lower (E), the largest element less than or equal to e; // returns e ceiling (E ); // returns the smallest element e higher (E) greater than or equal to e. // returns the smallest element greater than e.
Compared with the view method in SortedSet, NavigableSet adds some methods to specify whether the returned value contains the boundary value in a more explicit way, such:
NavigableSet<E> headSet(E toElement, boolean inclusive);NavigableSet<E> tailSet(E fromElement, boolean inclusive);NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
NavigableSet also adds two operations to the beginning and end:
E pollFirst (); // return and delete the first element E pollLast (); // return and delete the last element
In addition, NavigableSet provides the following methods to facilitate reverse access:
NavigableSet<E> descendingSet();Iterator<E> descendingIterator();
Let's take a look at a simple sample code to enhance the intuitive feeling and output the following annotations:
NavigableSet<String> set = new TreeSet<String>();set.addAll(Arrays.asList(new String[]{ "c", "a", "b", "d","f" }));System.out.println(set.floor("a")); //aSystem.out.println(set.lower("b")); //aSystem.out.println(set.ceiling("d"));//dSystem.out.println(set.higher("c"));//dSystem.out.println(set.subSet("b", true, "d", true)); //[b, c, d]System.out.println(set.pollFirst()); //aSystem.out.println(set.pollLast()); //fSystem.out.println(set.descendingSet()); //[d, c, b]
Other constructor Methods
Other TreeSet constructor methods are as follows:
public TreeSet(Collection<? extends E> c)public TreeSet(SortedSet<E> s)TreeSet(NavigableMap<E,Object> m)
The first two are based on an existing set and add all the elements to the current TreeSet. The difference is that in the first one, the comparator is null, assuming that the element implements the Comparable interface, in the second, the comparator is set to the same as that in the SortedSet parameter.
The third is not public and is used internally.
Basic implementation principle
As described in section 41, HashSet is implemented based on HashMap. The element is the key in HashMap. The value is a fixed value. TreeSet is similar. It is implemented based on TreeMap, let's take a look at the code and look at its internal composition first.
Internal components
The TreeSet contains the following members:
private transient NavigableMap<E,Object> m;private static final Object PRESENT = new Object();
M is the TreeMap behind it. Here we use the more general interface type NavigableMap, and the PRESENT is the fixed shared value.
The method implementation of TreeSet is mainly to call the m method. Let's take a look at it.
Constructor
The code for several constructor methods is:
TreeSet(NavigableMap<E,Object> m) { this.m = m;}public TreeSet() { this(new TreeMap<E,Object>());}public TreeSet(Comparator<? super E> comparator) { this(new TreeMap<>(comparator));}public TreeSet(Collection<? extends E> c) { this(); addAll(c);}public TreeSet(SortedSet<E> s) { this(s.comparator()); addAll(s);}
The code is relatively simple and will not be explained.
Add Element
The code for the add method is:
public boolean add(E e) { return m.put(e, PRESENT)==null;}
The put Method of map is called. Element e is used as the key, and the value is the fixed value 'present'. If 'put' is returned, null indicates that no corresponding key exists and is successfully added.
Check whether the element is included
Code:
public boolean contains(Object o) { return m.containsKey(o);}
Check whether the map contains the corresponding key.
Delete Element
Code:
public boolean remove(Object o) { return m.remove(o)==PRESENT;}
The remove Method of map is called. If the returned value is PRESENT, the corresponding key exists and the deletion is successful.
Subset View
Code of the subSet method:
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new TreeSet<>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));}
Call the subMap method to obtain the subset of NavigatebleMap, and then call the internal TreeSet constructor.
Head and end operations
Code:
public E first() { return m.firstKey();}public E last() { return m.lastKey();} public E pollFirst() { Map.Entry<E,?> e = m.pollFirstEntry(); return (e == null) ? null : e.getKey();}public E pollLast() { Map.Entry<E,?> e = m.pollLastEntry(); return (e == null) ? null : e.getKey();}
The code is relatively simple and will not be explained.
Reverse Traversal
Code:
public Iterator<E> descendingIterator() { return m.descendingKeySet().iterator();}public NavigableSet<E> descendingSet() { return new TreeSet<>(m.descendingMap());}
It is also very simple.
Implementation principle Summary
The implementation code of TreeSet is relatively simple. It is mainly used to call the internal NavigatableMap method.
TreeSet features
Compared with HashSet, TreeSet also implements the Set interface, but is implemented based on TreeMap internally, and TreeMap is based on the roughly balanced sorting Binary Tree-the red and black tree, which determines that it has the following features:
- No repeated Elements
- It is highly efficient to add or delete elements and determine whether they exist. The values are O (log2 (N) and N is the number of elements.
- In order, TreeSet also implements the SortedSet and NavigatableSet interfaces, allowing you to conveniently search and operate in order, for example, the first, last, a value range, and Adjacent Elements of a value.
- For the sake of order, TreeSet requires that the element implement the Comparable interface or provide a Comparator object through the constructor.
Summary
This section describes the usage and implementation principles of TreeSet. In terms of usage, it implements the Set interface, but is ordered. It also implements the SortedSet and NavigatableSet interfaces, and implements internal implementation, it uses TreeMap, and the code is relatively simple.
So far, we have introduced the main common container interfaces and implementation classes in Java. The interfaces mainly include Queue, Deque, List, Map, and Set, implementation classes include ArrayList, rule list, HashMap, TreeMap, HashSet, and TreeSet.
There are other implementation classes in the interfaces Queue, Deque, Map, Set, and Java container classes, which have their own characteristics. Let's continue to explore in the following sections.
---------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Retain All copyrights with original intent.