1

I'm looking at this code: https://www.geeksforgeeks.org/bridge-in-a-graph/

Iterator<Integer> i = adj[u].iterator();
while (i.hasNext())
{
    int v = i.next();  // v is current adjacent of u
    ...

Why didn't the author just use a for loop? Wouldn't this be the same?

for (int v: adj[u])
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Atlas2k
  • 381
  • 2
  • 13
  • Please include the definition of `adj`. Collection iterators can do certain things which enhanced for loops cannot, e.g. delete from the collection while iterating. This must be a duplicate of some other question. – Tim Biegeleisen Jan 26 '18 at 01:43
  • 4
    "Why didn't the author just use a for loop?" You should ask the author, we can't look inside the author's mind. Possible reasons: the code might be very old, from before the enhanded for-loop was introduced. Or the author is not familiar with Java and used whatever they knew about it. For anyone else than the author, this is an opinion-based question. – Erwin Bolwidt Jan 26 '18 at 01:47
  • 1
    @ErwinBolwidt Or maybe OP isn't sure they're equivalent. – shmosel Jan 26 '18 at 01:53
  • They are the same ... unless the "..." code is doing something with the iterator. – Stephen C Jan 26 '18 at 01:56
  • @shmosel I wasn't sure if they're equivalent. Thanks – Atlas2k Jan 26 '18 at 05:57

1 Answers1

6

In Java, one use of Iterator<E> is to remove elements from a Collection<E> while iterating. If you were to attempt to remove the same element from the same Collection while iterating over it with for (int v : adj[u]), then a ConcurrentModificationException would be thrown.

If no element is being removed, then yes, both choices of syntax would suffice.

As for why the author of that article didn't use a for-loop, you'd have to ask them. Their code doesn't seem to be removing any elements from the LinkedList<Integer> within the loop, so it was most likely a subconscious choice.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116