如何在 Java 中遍歷任意對映?


以下示例使用 Collection 類的 iterator 方法遍歷 HashMap。

示例

 線上演示

import java.util.*;

public class Main {
   public static void main(String[] args) {
      HashMap< String, String> hMap = new HashMap< String, String>();
      hMap.put("1", "1st");
      hMap.put("2", "2nd");
      hMap.put("3", "3rd");
      Collection cl = hMap.values();
      Iterator itr = cl.iterator();

      while (itr.hasNext()) {
         System.out.println(itr.next());
      }
   }
}

輸出

以上程式碼示例將產生以下結果。

1st
2nd
3rd

更新於: 2020 年 6 月 22 日

162 次觀看

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告