What is the correct way to iterate over a HashSet?

Last Updated :
Discuss
Comments

What is the correct way to iterate over a HashSet?


Java
for (int i = 0; i < hashSet.size(); i++) {
    System.out.println(hashSet.get(i));
}


Java
Iterator<String> it = hashSet.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}


Java
for (String item : hashSet) {
    System.out.println(item);
}


Both B and C

Share your thoughts in the comments