java中Set的用法
发布日期:2021-05-09 08:19:51 浏览次数:11 分类:博客文章

本文共 796 字,大约阅读时间需要 2 分钟。

Set集合的特点:

不能存储相同的元素。

同时因为其是一个抽象的接口:所以不能直接实例化一个set对象。(Set s = new Set() )错误

该接口主要继承于Collections接口,所以具有Collection的一些常见的方法。

常见的方法:

Sr.No. Method & Description
1

add( )         向集合中添加元素

2

clear( )        去掉集合中所有的元素

3

contains( )    判断集合中是否包含某一个元素

4

isEmpty( )    判断集合是否为空

5

iterator( )    主要用于递归集合,返回一个Iterator()对象

6

remove( )    从集合中去掉特定的对象

7

size( )        返回集合的大小

Set接口最长用的两大实现:HashSet     TreeSet

TreeSet:会将里面的元素默认排序。

 

Set
test = new TreeSet<>();int a = 1;int b = 8;int c = 3; test.add(a);test.add(b);test.add(c); //遍历集合test 利用foreach遍历 //输出结果:1 3 8 for (Integer value : test) { System.out.print(value+" "); } //利用Iterator实现遍历Iterator
value = test.iterator();while (value.hasNext()) { int s = value.next(); System.out.print(s+" ");} //输出结果:1 3 8

 

上一篇:java中数据类型的范围
下一篇:java中StringBuffer与String、StringBuilder的区别

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月21日 06时39分04秒