企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 如何迭代`Set`/`HashSet` > 原文: [https://beginnersbook.com/2014/08/how-to-iterate-over-a-sethashset/](https://beginnersbook.com/2014/08/how-to-iterate-over-a-sethashset/) 迭代`HashSet`有两种方法: 1)使用`Iterator` 2)不使用`Iterator` #### 示例 1:使用迭代器 ```java import java.util.HashSet; import java.util.Iterator; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); Iterator<String> it = hset.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } ``` **输出:** ```java Chaitanya Rick Harry Rahul Tim ``` ### 示例 2:不使用迭代器迭代 ```java import java.util.HashSet; import java.util.Set; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet Set<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); for (String temp : hset) { System.out.println(temp); } } } ``` **输出:** ```java Chaitanya Rick Harry Rahul Tim ```