I have a foreach loop in Java (simplified version here)
List<String> names = getNames();
for(String name:names) {
doSomething(name);
}
Is there an automated way to refactor this to a traditional for
loop?
I know how to do it manually
List<String> names = getNames();
for(int i=0; i<names.size(); i++) {
String name = names.get(i);
doSomething(name);
}
As you can see, there is a bit of typing needed in the for
statement itself as well as introducing the variable name
again and assign it the value names.get(i)
. In total, the manual edit is too error-prone for me.
Why do I want to do this? I have to fix a bug and the fix is to start at index 1 instead of index 0 and end at index n-1 instead of the end (unfortunately I can't fix the input right away, I need to wait for a library update if that's recognized as a bug).
What have I tried? I right-clicked on the for
keyword and clicked on "Refactor", but as far as I can get from the context menu entries, nothing in there would do the work for me.
Why do I think this could theoretically work? Because similar functionality exists in Resharper for Visual Studio (C#).
FYI: I'm using Eclipse Luna SR 2 (4.4.2)
Mouseover the
for
statement, right-click, Quick fix (Ctrl+1), convert to indexed loop.Should work!