原文: https://beginnersbook.com/2014/08/how-to-iterate-over-a-sethashset/

迭代HashSet有两种方法:

1)使用Iterator

2)不使用Iterator

示例 1:使用迭代器

  1. import java.util.HashSet;
  2. import java.util.Iterator;
  3. class IterateHashSet{
  4. public static void main(String[] args) {
  5. // Create a HashSet
  6. HashSet<String> hset = new HashSet<String>();
  7. //add elements to HashSet
  8. hset.add("Chaitanya");
  9. hset.add("Rahul");
  10. hset.add("Tim");
  11. hset.add("Rick");
  12. hset.add("Harry");
  13. Iterator<String> it = hset.iterator();
  14. while(it.hasNext()){
  15. System.out.println(it.next());
  16. }
  17. }
  18. }

输出:

  1. Chaitanya
  2. Rick
  3. Harry
  4. Rahul
  5. Tim

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

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. class IterateHashSet{
  4. public static void main(String[] args) {
  5. // Create a HashSet
  6. Set<String> hset = new HashSet<String>();
  7. //add elements to HashSet
  8. hset.add("Chaitanya");
  9. hset.add("Rahul");
  10. hset.add("Tim");
  11. hset.add("Rick");
  12. hset.add("Harry");
  13. for (String temp : hset) {
  14. System.out.println(temp);
  15. }
  16. }
  17. }

输出:

  1. Chaitanya
  2. Rick
  3. Harry
  4. Rahul
  5. Tim