在Java中重用循环中变量的首选方法

Ale*_*sky 2 java idioms

出于以下情况,这是重用section矢量的首选方式?

Iterator<Vector> outputIter = parsedOutput.iterator();

while(outputIter.hasNext()) {
    Vector section = outputIter.next();
}
Run Code Online (Sandbox Code Playgroud)

要么

Vector section = null;

while(outputIter.hasNext()) {
    section = outputIter.next();
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*zak 9

第二种方式意味着变量section在循环外可见.如果你没有在循环之外使用它,那么就没有必要这样做,所以使用第一个选项.就性能而言,应该没有任何明显的差异.


Axe*_*xel 8

我更喜欢第二个版本,因为在循环结束后你的范围内没有未使用的变量.

但是,怎么样

for (Vector section: parsedOutput) {
    ...
}
Run Code Online (Sandbox Code Playgroud)