The not-so-enhanced for loop
Posted July 6th, 2010 by CarlosIn Java, there’s a loop construct called “enhanced for loop” (it’s just a foreach, don’t get too excited). I decided to use it in the obvious, straightforward way thus:
for(String str : words){
str = doSomething(str);
}
return words;
Many will see the problem already. In Java, a variable doesn’t hold your data, everything (except for the built-in numbers) is a pointer. So, what does this code actually do? Instead of processing the strings in the words array (or other enumerable class) and copying them back, the strings in words don’t change at all.
You see, in each iteration, the str variable points to the nth string in the array. When you assign str a new value (I take a StringBuilder and return its string back, as I’m trimming special characters), it happily points somewhere else, leaving the original one intact.
Remember kids, if you want to use for loops, you might have to go the old-fashioned way to make sure the entries in your array are updated. For reference, this is the correct code:
for(int i = 0; i < words.length; ++i){
words[i] = doSomething(words[i]);
}
return words;
What I can’t figure out is why the (bytecode) compiler doesn’t do this itself.
Tags: for, for-loop, java, programming
Leave a Reply