Tuesday, March 1, 2016

Java: Best way to iterate through an Collection

  1. If you have an iterable and need to traverse unconditionally to all of them:
    for (iterable_type iterable_element : collection)
  2. If you have an iterable but need to conditionally traverse:
    for (Iterator iterator = collection.iterator(); iterator.hasNext();)
  3. If data-structure does not implement iterable:
    for (int i = 0; i < collection.length; i++)