Photo of David Winter

david winter

Java foreach loop

Coming from a PHP background, it’s always annoyed me that I can’t use something as simple as a foreach() loop in my C++/Java applications.

However, with a recent lecture on the Collections API and Generics, that’s all changed as I’ve found the Java equivalent!

Vector<Employee> myVector = new Vector<Employee>();
for (Employee person : myVector)
{
    System.out.println(person.getName());
}

Which is the same as doing something nasty like:

Vector<Employee> myVector = new Vector<Employee>();
for (int i = 0; i < myVector.size(); i++)
{
    System.out.println(myVector.get(i).getName());
}

Saves a ton of time.