我想要两个不同类型的循环变量。有什么办法可以让这个工作吗?
@Override
public T get(int index) throws IndexOutOfBoundsException {
// syntax error on first 'int'
for (Node<T> current = first, int currentIndex; current != null;
current = current.next, currentIndex++) {
if (currentIndex == index) {
return current.datum;
}
}
throw new IndexOutOfBoundsException();
}
The 初始化一个for http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.1声明遵循以下规则局部变量声明 http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.4.
这是合法的(如果愚蠢的话):
for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
// something
}
但试图宣告独特Node
and int
您想要的类型对于局部变量声明是不合法的。
您可以使用如下块来限制方法内附加变量的范围:
{
int n = 0;
for (Object o = new Object();/* expr */;/* expr */) {
// do something
}
}
这可确保您不会意外地在方法的其他地方重用该变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)