Java:在for循环init中初始化多个变量? [英] Java: Initialize multiple variables in for loop init?

查看:56
本文介绍了Java:在for循环init中初始化多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要两个不同类型的循环变量.有什么办法可以让这个工作吗?

I want to have two loop variables of different types. Is there any way to make this work?

@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();
}

推荐答案

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

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

This would be legal (if silly):

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

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

But trying to declare the distinct Node and int types as you want is not legal for local variable declarations.

您可以使用这样的块来限制方法中附加变量的范围:

You can limit the scope of additional variables within methods by using a block like this:

{
  int n = 0;
  for (Object o = new Object();/* expr */;/* expr */) {
    // do something
  }
}

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

This ensures that you don't accidentally reuse the variable elsewhere in the method.

这篇关于Java:在for循环init中初始化多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆