Java – refactoring foreach to for loop

I have a Java foreach loop (here is a simplified version)

List<String> names = getNames();
for(String name:names) {
    doSomething(name);
}

Is there an automatic way to refactor it into 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, the for statement itself needs to enter something and reintroduce the variable name and assign it names get(i). In general, manual editing is too error prone for me

Why should I do this? I have to fix an error. The fix starts at index 1 instead of index 0 and ends at index n-1 instead of ending (unfortunately, I can't fix the input immediately. I need to wait for the library update if it is considered a bug)

What have I tried? I right-click the for keyword and click refactor, but as far as I get from the context menu item, nothing there will work for me

Why do I think this is feasible in theory? Because similar functions exist in resharper for Visual Studio (c#)

For reference only: I am using eclipse Luna Sr 2 (4.4.2)

Solution

Hover over the for statement, right-click, quick repair (ctrl 1), and convert to index loop

It should work!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>