Java Tip #1: foreach with index

When you are working with Java some hours each day, you soon develop an own programming style and collect some ideas how to make your code nicer. From time to time, I’ll present some of my most favorite ideas here.

Today, let’s look at the foreach loop. I guess, you often use code like this:

for (int i = 0; i < list.size(); i++) {
  Element e = list.get(i);

Not really nice, is it? As Java programmers we are used to read and understand such code quickly, but there must be a better way, since what we want to say is only “For each element of the list…”. But hey, we have the foreach loop since Java 5:

for (Element e : list) {

Very nice, isn’t it? Unfortunately we have lost the index of the current element now, which was stored in the variable i before. For this, I’m using two solutions. The first one is using a custom iterator, which I will explain in a later Java Tip. The second one is using an index together with foreach, that runs over a Range (use import static of the Range.range method):

for (int i : range(list)) {
  Element e = list.get(i);

Though we do not get a one-liner, we get rid of the increment at least. The Range class is also very useful for other cases, for example when counting from 1 to 10:

for (int i : range(1, 10)) {

Downloads: Range

Advertisements

3 Responses to Java Tip #1: foreach with index

  1. Kosi2801 says:

    This looks very interesting. But the download link to Range.java seems to lead to an empty html file, is this correct?

  2. Andi says:

    Thank you for this hint! The link was correct but only worked when you have a login for the tracker. I exchanged the link, now the problem should be gone.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s