從 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]

更新於: 25-6 月 -2020

335 個觀看

推動你的職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.