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?