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.

2005-12-08 [, ]

Comments

  1. Thanks mate, been looking for this!

    Mattias (2008-10-07 @ 10:04)
  2. Nice! – knew you must have been able to do something less ugly than the latter!

    Chris (2009-05-25 @ 06:21)

Powered by WP Hashcash