前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java sortedset用法_Java SortedSet headSet()用法及代码示例[通俗易懂]

java sortedset用法_Java SortedSet headSet()用法及代码示例[通俗易懂]

作者头像
全栈程序员站长
发布2022-09-27 16:01:20
4860
发布2022-09-27 16:01:20
举报
文章被收录于专栏:全栈程序员必看

Java中的SortedSet接口的headSet()方法用于返回此集合中其元素严格小于参数toElement的部分的视图。

此方法返回的集合由该集合支持,因此返回集合中的更改会反映在该集合中,反之亦然。

此方法返回的set支持此set支持的所有可选set操作。

注意:如果试图插入超出其范围的元素,则此方法返回的集合将引发IllegalArgumentException。

用法:

SortedSet headSet(E toElement)

其中,E是此Set维护的元素的类型。

参数:此函数接受单个参数toElement,该参数表示返回集的高端端点(不包括)。

返回值:返回当前集合中的最后一个或最高元素。

异常:

ClassCastException:如果toElement与该集合的比较器不兼容(或者,如果集合没有比较器,则toElement不实现Comparable),则抛出ClassCastException。

NullPointerException:如果参数toElement为null,则抛出NullPointerException。

IllegalArgumentException:它引发一个IllegalArgumentException,此集合本身具有限制范围,并且参数toElement位于范围的范围之外。

以下示例程序旨在说明上述方法:

程序1:

// A Java program to demonstrate

// working of SortedSet

import java.util.SortedSet;

import java.util.TreeSet;

public class Main {

public static void main(String[] args)

{

// Create a TreeSet and inserting elements

SortedSet s = new TreeSet<>();

// Adding Element to SortedSet

s.add(1);

s.add(5);

s.add(2);

s.add(3);

s.add(9);

// Returning the set with elements

// strictly less than the passed value

System.out.print(“Elements strictly less than 7 in set are : “

+ s.headSet(7));

}

}

输出:

Elements strictly less than 7 in set are : [1, 2, 3, 5]

程序2:

// A Java program to demonstrate

// working of SortedSet

import java.util.SortedSet;

import java.util.TreeSet;

public class Main {

public static void main(String[] args)

{

// Create a TreeSet and inserting elements

SortedSet s = new TreeSet<>();

// Adding Element to SortedSet

s.add(“Geeks”);

s.add(“For”);

s.add(“Geeks”);

s.add(“Code”);

s.add(“It”);

// Returning the set with elements

// strictly less than the passed value

System.out.print(“Element strictly less than Z in set is : “

+ s.headSet(“Z”));

}

}

输出:

Element strictly less than Z in set is : [Code, For, Geeks, It]

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/184404.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档