要从TreeSet获取HeadSet,首先创建一个TreeSet并添加一些元素:
TreeSet<String> treeSet = new TreeSet<String>(); treeSet.add("ABC"); treeSet.add("DEF"); treeSet.add("GHI"); treeSet.add("JKL"); treeSet.add("MNO"); treeSet.add("PQR");
要获取耳机,请使用以下headset()
方法:
SortedSet<String> set = treeSet.headSet("MNO"); System.out.println("Head Set = " + set);
您还可以像这样更改值:
set = treeSet.headSet("GHI"); System.out.println("Head Set = " + set);
import java.util.SortedSet; import java.util.TreeSet; public class Demo { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<String>(); treeSet.add("ABC"); treeSet.add("DEF"); treeSet.add("GHI"); treeSet.add("JKL"); treeSet.add("MNO"); treeSet.add("PQR"); SortedSet<String> set = treeSet.headSet("MNO"); System.out.println("Head Set = " + set); set = treeSet.headSet("GHI"); System.out.println("Head Set = " + set); set = treeSet.headSet("ABC"); System.out.println("Head Set = " + set); } }
输出结果
Head Set = [ABC, DEF, GHI, JKL] Head Set = [ABC, DEF] Head Set = []