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
This looks very interesting. But the download link to Range.java seems to lead to an empty html file, is this correct?
Found it in the meantime, the correct link would be http://tracker.zong-music.com/projects/tracker/repository/revisions/master/entry/util/src/com/xenoage/util/Range.java right?
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.