声明一个HashSet并添加元素-
Set hs = new HashSet(); hs.add(20); hs.add(39); hs.add(67); hs.add(79);
现在,遍历元素-
for (Iterator i = hs.iterator(); i.hasNext();) { Object ele = i.next(); System.out.println(ele); }
以下是一个迭代HashSet元素的示例-
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Demo { public static void main(String[] argv) throws Exception { Set hs = new HashSet(); hs.add(20); hs.add(39); hs.add(67); hs.add(79); System.out.println("Elements = "); for (Iterator i = hs.iterator(); i.hasNext();) { Object ele = i.next(); System.out.println(ele); } } }
输出结果
Elements = 67 20 39 79