從 Java 集合中檢索元素 - Iterator


以下是一個用於檢索元素的示例 -

示例

 即時演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet<String> my_hs = new HashSet<String>() ;
      my_hs.add("Joe");
      my_hs.add ("Rob");
      Iterator my_it = my_hs.iterator();
      System.out.println("The elements are : ");
      while (my_it.hasNext())
         System.out.println(my_it.next());
   }
}

輸出

The elements are :
Joe
Rob

一個名為 Demo 的類包含定義了一個 HashSet 集合的主函式。使用“add”函式向此集合新增元素。定義了一個迭代器,並透過使用“hasNext”函式檢查是否有下一個元素來對元素進行迭代。元素顯示在螢幕上。

更新於: 2020-9-14

301 次瀏覽

啟動您的 職業

完成課程,獲得證書

開始
廣告
© . All rights reserved.