Java 简明教程
Java TreeSet Class
Introduction
Java TreeSet 类实现了 Set 接口。以下是有关 TreeSet 的要点 −
The Java TreeSet class implements the Set interface. Following are the important points about TreeSet −
-
The TreeSet class guarantees that the Map will be in ascending key order and backed by a TreeMap.
-
The Map is sorted according to the natural sort method for the key Class, or by the Comparator provided at set creation time, that will depend on which constructor used.
-
The ordering must be total in order for the Tree to function properly.
Class declaration
以下是 java.util.TreeSet 类的声明 −
Following is the declaration for java.util.TreeSet class −
public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
Parameters
以下是 java.util.TreeSet 类的参数 −
Following is the parameter for java.util.TreeSet class −
E − 这是该集合维护的元素类型。
E − This is the type of elements maintained by this set.
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractSet
-
java.util.AbstractCollection
-
java.util.Object
-
java.util.Set
Adding Entries to a TreeSet Example
以下示例显示了使用 Java TreeSet add() 方法向树集添加实体的用法。我们创建了一个 Integer 的 TreeSet 对象。然后使用 add() 方法添加了一些实体,并打印出树集对象以检查其内容。
The following example shows the usage of Java TreeSet add() method to add entries to the treeset. We’ve created a TreeSet object of Integer. Then few entries are added using add() method and treeset object is printed to check its content.
package com.tutorialspoint;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
// creating a TreeSet
TreeSet<Integer> treeset = new TreeSet<>();
// adding in the tree set
treeset.add(12);
treeset.add(13);
treeset.add(14);
treeset.add(15);
// displaying the Tree set data
System.out.print("Tree set : " + treeset);
}
}