JDT provides a quickfix for converting classic for loops into enhanced for loops. When using a classic for loop to iterate through the elements of an iterator calling next() within the loop body but not using its result (such as when only counting the elements), applying the quickfix for converting into an enhanced for loop leads to syntactically incorrect code.
Example
Original code:
List<Object> list = new ArrayList<>();
int i = 0;
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
iterator.next();
i++;
}
After applying the quickfix:
List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
object;
i++;
}
object; is an invalid statement.
Reproduction Environment
Happens with Eclipse 2023-09 and JDK 17.
Expected Behavior
The quick fix should always produce syntactically (and semantically) correct code. For the given example, the quick fix should either not be provided or the result should look as follows:
List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
i++;
}
Additional Information
The invalid result only occurs when performing the next() call within the loop body. When performing it within the loop header, the refactoring result is correct, e.g.:
Original code:
List<Object> list = new ArrayList<>();
int i = 0;
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext(); iterator.next()) {
i++;
}
After applying the quickfix:
List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
i++;
}
Issue: https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/1008
Current Behavior
JDT provides a quickfix for converting classic
for
loops into enhanced for loops. When using a classicfor
loop to iterate through the elements of an iterator callingnext()
within the loop body but not using its result (such as when only counting the elements), applying the quickfix for converting into an enhancedfor
loop leads to syntactically incorrect code.Example
Original code:
After applying the quickfix:
object;
is an invalid statement.Reproduction Environment
Happens with Eclipse 2023-09 and JDK 17.
Expected Behavior
The quick fix should always produce syntactically (and semantically) correct code. For the given example, the quick fix should either not be provided or the result should look as follows:
Additional Information
The invalid result only occurs when performing the
next()
call within the loop body. When performing it within the loop header, the refactoring result is correct, e.g.:Original code:
After applying the quickfix: