headSet是TreeSet的视图方法,返回严格小于指定元素的动态子集,原集合变更时自动更新;支持单参数(不含toElement)和双参数(含inclusive标志)两种调用方式。

headSet 是 TreeSet 提供的视图方法,用于获取所有严格小于指定元素的子集,返回的是原集合的动态视图——原集合变化时,该子集也会同步更新。
基本用法:传入一个元素参数
调用 headSet(E toElement) 即可。注意:返回集合不包含 toElement 本身,只包含所有 小于 它的元素。
- 要求 toElement 必须能与 TreeSet 中元素比较(实现 Comparable 或构造时传入 Comparator)
- 若 toElement 不在集合中,也不影响结果;只要比较逻辑成立,就按大小关系截取
- 返回的仍是 TreeSet 类型(实际是 NavigableSubSet),支持进一步导航操作
示例代码
比如有一个升序 TreeSet 存储整数:
TreeSet<Integer> set = new TreeSet<>(Arrays.asList(1, 3, 5, 7, 9));
SortedSet<Integer> head = set.headSet(6); // 返回 {1, 3, 5}
System.out.println(head); // [1, 3, 5]
再插入一个元素到原集合:
立即学习“Java免费学习笔记(深入)”;
set.add(4); System.out.println(head); // 自动变为 [1, 3, 4, 5]
注意边界与异常
如果传入的 toElement 为 null,且 TreeSet 不接受 null(默认自然排序或 comparator 不允许 null),会抛出 NullPointerException。
- 若 TreeSet 使用自定义 Comparator,确保它能处理 toElement
- 若 toElement 比所有元素都小,headSet 返回空集合(非 null)
- 若比所有元素都大,返回整个 TreeSet 的视图
配合 boolean 参数的重载版本(Java 6+)
可用 headSet(E toElement, boolean inclusive) 控制是否包含 toElement:
- inclusive = true:返回 ≤ toElement 的子集(需 TreeSet 支持,且 toElement 存在或可插入)
- inclusive = false:等价于单参数版本,即 < toElement
TreeSet<String> words = new TreeSet<>(Arrays.asList("apple", "banana", "cherry"));
SortedSet<String> h1 = words.headSet("banana", false); // ["apple"]
SortedSet<String> h2 = words.headSet("banana", true); // ["apple", "banana"]


















