Just like HashSet is implemented based on HashMap, TreeSet is also implemented based on TreeMap. In "Java Improvement Chapter (27) -----TreeMap", LZ explained the TreeMap implementation mechanism in detail. If you have read this blog post in detail or have a more detailed understanding of TreeMap, then the implementation of TreeSet will be useful to you. It's as simple as drinking water.
1. TreeSet definition
We know that TreeMap is an ordered binary tree, so similarly TreeSet is also ordered, and its function is to provide an ordered Set collection. Through the source code, we know that TreeSet is based on AbstractSet, which implements NavigableSet, Cloneable, and Serializable interfaces. Among them, AbstractSet provides the backbone implementation of the Set interface, thus minimizing the work required to implement this interface. NavigableSet is an extension of SortedSet
with navigation methods that report the closest match for a given search target, which means it supports a range of navigation methods. For example, find the best match for a specified target. Cloneable supports cloning, and Serializable supports serialization.
public class TreeSet<e> extends AbstractSet<e> implements NavigableSet<e>, Cloneable, java.io.Serializable</e></e></e>
At the same time, the following variables are defined in TreeSet.
private transient NavigableMap<e> m; //PRESENT会被当做Map的value与key构建成键值对 private static final Object PRESENT = new Object();</e>
Its construction method:
//默认构造方法,根据其元素的自然顺序进行排序 public TreeSet() { this(new TreeMap<e>()); } //构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。 public TreeSet(Comparator super E> comparator) { this(new TreeMap(comparator)); } //构造一个新的空 TreeSet,它根据指定比较器进行排序。 public TreeSet(Collection extends E> c) { this(); addAll(c); } //构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。 public TreeSet(SortedSet<e> s) { this(s.comparator()); addAll(s); } TreeSet(NavigableMap<e> m) { this.m = m; }</e></e></e>
2. Main methods of TreeSet
1, add: Add the specified element to this set (if the element does not already 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> map = (TreeMap<e>) 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); }</e></e>
3, ceiling: Returns the smallest element in this set that is greater than or equal to the given element; if there is no such element, then Return null.
public E ceiling(E e) { return m.ceilingKey(e); }
4, clear: Remove all elements in this set.
public void clear() { m.clear(); }
5. Clone: Returns a shallow copy of the TreeSet instance. It is a shallow 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; }</e></e>
6. comparator: Returns a comparator that sorts the elements in this set; returns null if this set uses the natural ordering of its elements.
public Comparator super E> comparator() { return m.comparator(); }
7. contains: If this set contains the specified element, returns true.
public boolean contains(Object o) { return m.containsKey(o); }
8、descendingIterator:返回在此 set 元素上按降序进行迭代的迭代器。
public Iterator<e> descendingIterator() { return m.descendingKeySet().iterator(); }</e>
9、descendingSet:返回此 set 中所包含元素的逆序视图。
public NavigableSet<e> descendingSet() { return new TreeSet(m.descendingMap()); }</e>
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); }</e>
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(); }</e>
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(); }</e>
19、pollLast:获取并移除最后一个(最高)元素;如果此 set 为空,则返回 null。
public E pollLast() { Map.Entry<e> e = m.pollLastEntry(); return (e == null) ? null : e.getKey(); }</e>
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)); } /** * 返回此 set 的部分视图,其元素从 fromElement(包括)到 toElement(不包括)。 */ public SortedSet<e> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); }</e></e>
23、tailSet:返回此 set 的部分视图
/** * 返回此 set 的部分视图,其元素大于(或等于,如果 inclusive 为 true)fromElement。 */ public NavigableSet<e> tailSet(E fromElement, boolean inclusive) { return new TreeSet(m.tailMap(fromElement, inclusive)); } /** * 返回此 set 的部分视图,其元素大于等于 fromElement。 */ public SortedSet<e> tailSet(E fromElement) { return tailSet(fromElement, true); }</e></e>
三、最后
由于TreeSet是基于TreeMap实现的,所以如果我们对treeMap有了一定的了解,对TreeSet那是小菜一碟,我们从TreeSet中的源码可以看出,其实现过程非常简单,几乎所有的方法实现全部都是基于TreeMap的。
以上就是Java提高篇(二八)------TreeSet的内容,更多相关内容请关注PHP中文网(www.php.cn)!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.