Java 集合 如何迭代Set/HashSet

来源:这里教程网 时间:2026-02-17 20:13:29 作者:

迭代HashSet有两种方法:

1)使用Iterator

2)不使用Iterator

示例 1:使用迭代器

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());     }  }}

输出:

ChaitanyaRickHarryRahulTim

示例 2:不使用迭代器迭代

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);     }  }}

输出:

ChaitanyaRickHarryRahulTim

相关推荐