头戴式耳机 Java中的NavigableSet接口 用于返回该集合中元素小于(或等于,如果inclusive为true)toElement的部分的视图。
null
- 返回的集合由该集合支持,因此返回集合中的更改会反映在该集合中,反之亦然。
- 返回的集合支持该集合支持的所有可选集合操作。
笔记 :如果试图在其范围外插入元素,返回的集合将抛出IllegalArgumentException。
语法 :
NavigableSet<E> headSet(E toElement, boolean inclusive)
其中,E是该集合容器维护的元素类型。
参数 :此功能有两个参数:
- 托伦 –返回集的高端
- 包含全部费用 –如果高端要包含在返回的视图中,则为true
返回值 :它返回该集合中元素小于(或等于,如果inclusive为true)toElement的部分的视图。
下面的程序演示了Java中的headSet()方法:
方案1 :带有整数元素的NavigableSet。
// A Java program to demonstrate // headSet() method of NavigableSet import java.util.NavigableSet; import java.util.TreeSet; public class GFG { public static void main(String[] args) { NavigableSet<Integer> ns = new TreeSet<>(); ns.add( 0 ); ns.add( 1 ); ns.add( 2 ); ns.add( 3 ); ns.add( 4 ); ns.add( 5 ); ns.add( 6 ); System.out.println( "Map with key-value less than " + "given argument : " + ns.headSet( 6 )); System.out.println( "Map with key-value less than or" + " equal to given argument : " + ns.headSet( 6 , true )); } } |
输出:
Map with key-value less than given argument : [0, 1, 2, 3, 4, 5] Map with key-value less than or equal to given argument : [0, 1, 2, 3, 4, 5, 6]
项目2: 带有字符串元素的NavigableSet。
// A Java program to demonstrate // headSet?() method of NavigableSet import java.util.NavigableSet; import java.util.TreeSet; public class GFG { public static void main(String[] args) { NavigableSet<String> ns = new TreeSet<>(); ns.add( "A" ); ns.add( "B" ); ns.add( "C" ); ns.add( "D" ); ns.add( "E" ); ns.add( "F" ); ns.add( "G" ); System.out.println( "Map with key-value less than" + " given argument : " + ns.headSet( "F" )); System.out.println( "Map with key-value less than " + "or equal to given argument : " + ns.headSet( "F" )); } } |
输出:
Map with key-value less than given argument : [A, B, C, D, E] Map with key-value less than or equal to given argument : [A, B, C, D, E]
参考 : https://docs.oracle.com/javase/10/docs/api/java/util/NavigableSet.html#headSet(E)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END