【问题标题】:Can you use array initialization in an enhanced for loop?可以在增强的 for 循环中使用数组初始化吗?
【发布时间】:2019-04-07 11:10:49
【问题描述】:

我正在尝试通过编写简洁的代码来改进我的代码风格。我喜欢 Java 增强的 for 循环,但在以下场景中我仍然觉得它过于冗长:

int one = 1;
int two = 2;
int three = 3;

int numbers[] = {one, two ,three};
for (int number : numbers) {
    System.out.println(number);
}

是否可以执行以下操作?

int one = 1;
int two = 2;
int three = 3;

for (int number : {one, two ,three}) {
    System.out.println(number);
}

在一般情况下,我有一些我想要迭代的同一个类的命名变量。之后,我不再使用它们的数组/列表了。

【问题讨论】:

    标签: java arrays for-loop


    【解决方案1】:

    你可以写:

    for (int number : new int[] {one, two ,three}) {
        System.out.println(number);
    }
    

    如果您使用的是 Java 9 或更高版本,也可以使用 List.of()

    for (int number : List.of(one, two ,three)) {
        System.out.println(number);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2013-10-28
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多