如何在 Java 中浏览 HashSet
Java 提供了 3 种在 Java 中浏览 HashSet 的方法:
- Foreach Loop
- While loop with Iterator
- While loop with java.util.Enumeration
以下示例收集了没有 Iterator 或有 Iterator 的 3 个情况,并打印结果:
接口 java.util.Enumeration 返回一个对象,该对象生成一系列元素并使用两种方法: hasMoreElements() 检查是否还有更多元素,如果有,它会使用 nextElement().
引用:
java.util.HashSet.iterator() 方法
JavaDoc: 枚举接口
import java.util.Collections;让我们看看运行这个程序会发生什么:
import java.util.Enumeration;
导入 java.util.HashSet;
import java.util.Iterator;
public class parcours_hashset {
public static void main(String[] args) {
HashSet<字符串>hset = 新的 HashSet<字符串>();
hset.add(he1”);
hset.add(he2”);
hset.add(he3”);
/*高级 For 循环*/
System.out.println(高级 For 循环”);
for(String s: hset)
System.out.println(s);
/*while+Iterator loop*/
System.out.println(while+Iterator loop”);
迭代器<字符串> it = hset.iterator();
while(it.hasNext())
System.out.println(it.next());
/*枚举*/
System.out.println(while+枚举循环”);
// 检索 Enumeration
Enumerationenumeration = Collections.enumeration(hset);
// 读取 HashSet
while(enumeration.hasMoreElements())
System.out.println(enumeration.nextElement());
}
}
Loop for advancedThe iterator() 用于通过 HashSet 或 Set 的元素获取迭代器。元素是混合返回的,没有任何特定的顺序。
he3
he1
he2
While+Iterator
he3
he1
he2
While+Enumeration Loop
he3
he1
he2
接口 java.util.Enumeration 返回一个对象,该对象生成一系列元素并使用两种方法: hasMoreElements() 检查是否还有更多元素,如果有,它会使用 nextElement().
引用:
java.util.HashSet.iterator() 方法
JavaDoc: 枚举接口