在 Java 中檢查 HashSet 中的元素


要在 Java 中檢查 HashSet 中是否存在元素,請使用 contains() 方法。

建立 HashSet −

HashSet hs = new HashSet();

向其中新增元素 −

hs.add("R");
hs.add("S");
hs.add("T");
hs.add("V");
hs.add("W");
hs.add("Y");
hs.add("Z");

若要查詢某個元素,例如此處所示的 S,請使用 contains() −

hs.contains("S")

以下是一個在 HashSet 中檢查元素的示例 −

示例

 即時演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the HashSet
      hs.add("R");
      hs.add("S");
      hs.add("T");
      hs.add("V");
      hs.add("W");
      hs.add("Y");
      hs.add("Z");
      System.out.println("Set = "+hs);
      System.out.println("Is character S part of the set? "+hs.contains("S"));
      System.out.println("Is character B part of the set? "+hs.contains("B"));
   }
}

輸出

Set = [R, S, T, V, W, Y, Z]
Is character S part of the set? true
Is character B part of the set? false

更新於: 30-Jul-2019

2 千多個瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.