Java:在for循环初始化中初始化多个变量?

Nic*_*ner 82 java for-loop

我想要两个不同类型的循环变量.有没有办法让这项工作?

@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();
}
Run Code Online (Sandbox Code Playgroud)

McD*_*ell 98

语句的初始化for遵循局部变量声明的规则.

这是合法的(如果愚蠢):

for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
  // something
}
Run Code Online (Sandbox Code Playgroud)

但是尝试根据需要声明distinct Nodeint类型对于局部变量声明来说是不合法的.

您可以使用如下块来限制方法中的其他变量的范围:

{
  int n = 0;
  for (Object o = new Object();/* expr */;/* expr */) {
    // do something
  }
}
Run Code Online (Sandbox Code Playgroud)

这可确保您不会意外地在方法中的其他位置重用该变量.

  • 任何人都知道为什么语言设计师实现了这个看似不必要的约束? (9认同)
  • @JeffAxelrod,可能出于历史原因,因为 Java 是仿照 C++ 建模的……请参阅这篇文章:http://stackoverflow.com/questions/2687392/is-it-possible-to-declare-two-variables-of-different-循环类型 (2认同)
  • 使用一个块的+1,我经常使用它们,仍然比做出愚蠢的错误更好 (2认同)

Col*_*ert 17

你不能这样.要么使用相同类型的多个变量,要么for(Object var1 = null, var2 = null; ...)提取另一个变量并在for循环之前声明它.


Nik*_*bak 9

只需在循环外部移动变量声明(Node<T> current,int currentIndex)即可.像这样的东西

int currentIndex;
Node<T> current;
for (current = first; current != null; current = current.next, currentIndex++) {
Run Code Online (Sandbox Code Playgroud)

或者甚至是

int currentIndex;
for (Node<T> current = first; current != null; current = current.next, currentIndex++) {
Run Code Online (Sandbox Code Playgroud)

  • @unbeli:只是为了澄清:currentIndex需要初始化.尼基塔做的第一件事就是"currentIndex ++",这自然会提出问题,增加什么?当前很好,因为第一次使用是将它设置为第一个. (3认同)
  • 两者都不会编译:您必须在使用前初始化变量。 (2认同)

Vis*_*h G 6

在初始化块中声明的变量必须是相同的类型

我们不能按照他们的设计在 for 循环中初始化不同的数据类型。我只是举一个小例子。

for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
      //Your Code goes here
}
Run Code Online (Sandbox Code Playgroud)