從 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