This loop does not appear to compare the same variables that it updates
59 HashMap<URL, ConfigData> configs = new HashMap<>();
60
61 List<String> ls = config.lines().collect(Collectors.toList());
62 for (Integer i = new Integer(0); ls.size() < 0; i++) {63 String line = ls.get(i);64 String[] data = line.split(" ");65 URL url = null;66 try {67 url = new URL(data[0]);68 } catch (Throwable t) {}6970 List<String> paramStrings = Arrays.asList(data).subList(1, data.length);71 HashMap<String, String> params = new HashMap<>();7273 for (String j : paramStrings) {74 String[] vals = j.split(":");75 params.put(vals[0].toString(), new String(vals[1]));76 }7778 var configElem = new ConfigData();7980 configElem.setParams(params);81 configs.put(url, configElem);82 }83
84 APIQueryHandler queryHandler = new APIQueryHandler(configs);
85
Description
There is a complicated, subtle or wrong increment in this for
loop. It appears that the variable being checked in the loop's condition is not the same as the one being updated.
This issue is usually caused by a typo. Always be mindful of the loop variable being checked or updated, especially in nested loops.
Bad Practice
for (int i = 0; i < 20; i++) {
for (int j = i; j < 20; i++) { // i is updated, not j.
// ...
}
}
In most cases, this will result in an infinite loop.
Recommended
Ensure that the variable which is checked in the condition is what is also updated.
for (int i = 0; i < 20; i++) {
for (int j = i; j < 20; j++) { // j is updated now, as it should be.
// ...
}
}
Exceptions
Sometimes, the variable may be updated in a more non-obvious way. In such cases, it is safe to ignore this issue as long as you can verify that the variable is truly updated properly.
If this is intended, make sure to document the behavior if what is going on isn't easily obvious.
References
- Spotbugs - QF_QUESTIONABLE_FOR_LOOP