在 Java 中新增元素到 HashSet


首先,建立一個 HashSet −

HashSet hs = new HashSet();

現在,使用 add() 方法新增一些元素。將元素設定為一個引數。此處,我們設定了字串 −

hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");

以下是在 HashSet 中新增元素的一個示例 −

示例

 線上演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println(hs);
   }
}

輸出

[A, B, C, D, E, F, K, M, N]

更新於: 30-7-2019

276 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告