让我们首先创建一个TreeSet并添加元素:
TreeSet<Integer> treeSet = new TreeSet<Integer>(); treeSet.add(10); treeSet.add(20); treeSet.add(30); treeSet.add(40); treeSet.add(50); treeSet.add(60); treeSet.add(70); treeSet.add(80); treeSet.add(90); treeSet.add(100);
现在,假设您需要将子集设置为50到70,然后对其使用subset()
:
SortedSet<Integer> sub = treeSet.subSet(50, 70); System.out.println("Sub Set = " + sub);
import java.util.TreeSet; import java.util.SortedSet; public class Demo { public static void main(String[] args) { TreeSet<Integer> treeSet = new TreeSet<Integer>(); treeSet.add(10); treeSet.add(20); treeSet.add(30); treeSet.add(40); treeSet.add(50); treeSet.add(60); treeSet.add(70); treeSet.add(80); treeSet.add(90); treeSet.add(100); SortedSet<Integer> sub = treeSet.subSet(50, 70); System.out.println("Sub Set = " + sub); sub = treeSet.subSet(80, 90); System.out.println("Sub Set = " + sub); sub = treeSet.subSet(10, 90); System.out.println("Sub Set = " + sub); } }
输出结果
Sub Set = [50, 60] Sub Set = [80] Sub Set = [10, 20, 30, 40, 50, 60, 70, 80]