从 Java 中的 HashSet 中移除指定元素
要从 HashSet 中移除指定元素,请使用 remove() 方法。
首先,声明一个 HashSet 并添加元素 −
Set<Integer> hs = new HashSet<Integer>(); hs.add(20); hs.add(39); hs.add(67); hs.add(79); hs.add(81); hs.add(87); hs.add(88);
假设你需要移除元素 39,为此,使用 remove() 方法 −
hs.remove(39);
下面是一个从 HashSet 中移除指定元素的示例 −
示例
import java.util.*;
public class Demo {
public static void main(String args[]) {
Set<Integer> hs = new HashSet<Integer>();
hs.add(20);
hs.add(39);
hs.add(67);
hs.add(79);
hs.add(81);
hs.add(87);
hs.add(88);
System.out.println("Elements = "+hs);
// remove specific elements
hs.remove(39);
System.out.println("Updated Elements = "+hs);
}
}输出
Elements = [81, 67, 20, 39, 87, 88, 79] Updated Elements = [81, 67, 20, 87, 88, 79]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
html
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP