Java 中的 Set 集合接口函数

首页 / Java入门教程 / Java 中的 Set 集合接口函数

Set集合是不能包含重复元素的集合,Set接口仅包含从Collection继承的方法,并增加了禁止重复元素的限制。

下表总结了Set声明的方法-

Sr.No.Method & Remark
1

add()

将对象添加到集合中。

2

clear()

从集合中删除所有对象。

3

contains()

如果指定对象是集合中的元素,则返回true。

4

isEmpty()

如果集合没有元素,则返回true。

5

iterator()

返回集合的Iterator对象,该对象可用于检索对象。

链接:https://www.learnfk.comhttps://www.learnfk.com/java/java-set-interface.html

来源:LearnFk无涯教程网

6

remove()

从集合中删除指定的对象。

7

size()

返回集合中的元素数。

Set 示例

Set在各种类(如HashSet,TreeSet,LinkedHashSet)中都有其实现。

无涯教程网

import java.util.*;
public class SetDemo {

  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);

         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
} 

这将产生以下输出-

[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

持续交付36讲 -〔王潇俊〕

深入拆解Java虚拟机 -〔郑雨迪〕

从0开始学大数据 -〔李智慧〕

ZooKeeper实战与源码剖析 -〔么敬国〕

OAuth 2.0实战课 -〔王新栋〕

Spark核心原理与实战 -〔王磊〕

etcd实战课 -〔唐聪〕

手把手带你写一个Web框架 -〔叶剑峰〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)