-1

I've been teached in college that one has to create an iterator to loop over a set.

java.util.HashSet<String> set = new java.util.HashSet<String>();

set.add("Green");
set.add("Blue");
set.add("Yellow");
set.add("Orange");
set.add("Red");

Iterator it = set.iterator();

while (it.hasNext()) {
    String current = (String) it.next();

    System.out.println(current);
}

Now I've seen in the code of colleagues that there is a more simple way to accomplish it. Using a for-loop:

for (String str : set) {
    System.out.println(str);
}

I asked myself why the approach with the for-loop wasn't showed in college.

Has the approach with the for-loop disadvantages?

What's the preferable way to iterate over a set and why?

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • 4
    Use the enhanced for loop if you don't need to remove from the set during iteration. – Andy Turner Nov 22 '16 at 10:35
  • 1
    And if you use the iterator approach, use `Iterator`, not raw `Iterator`. – Andy Turner Nov 22 '16 at 10:35
  • 2
    Did you see the link - http://stackoverflow.com/documentation/java/90/collections/5856/iterating-over-collections ??? – Chirag Parmar Nov 22 '16 at 10:36
  • Ahh, ... thanks. That makes sense. One needs the iterator to change the data structure while iterating over it. – cluster1 Nov 22 '16 at 10:36
  • No search effort: https://www.google.pl/search?q=java+why+use+iterator+instead+of+for+loop , http://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-iterator , http://stackoverflow.com/questions/22267919/iterator-vs-for , http://stackoverflow.com/questions/1879255/performance-of-traditional-for-loop-vs-iterator-foreach-in-java – Robert Niestroj Nov 22 '16 at 10:36

1 Answers1

2

There is no difference, as behind the scenes you'll still be using an iterator.

That is, the p-code will be more a less the same.

Andres
  • 10,561
  • 4
  • 45
  • 63