示例

public class ClassA {

public void methodA ( List list ) {

for ( Iterator it = list.iterator(); it.hasNext(); ) {

int anInteger = 2;
Object obj = it.next();

// do something with obj and anInteger...
}
}


解决方案
避免在循环中声明不依赖于循环条件的变量或对其赋值
可行的方法是在循环外部赋值变量,以避免发生额外开销。

public class ClassA {

public void methodA ( List list ) {

int anInteger = 2;
Object obj;
for ( Iterator it = list.iterator(); it.hasNext(); ) {

obj = it.next();

// do something with obj and anInteger...
}
}