是否可以在每个循环的条件区中初始化数组?

问题描述 投票:0回答:1

在python中,您可以这样做:

for item in [a, b, c, d]:
    some-code

在Java中,您可以在for循环条件区域中声明数组的情况下是否有类似的可能?

我的直觉是这样做:

public static void main(String[] args) {
    for (String string : String myArr[] = {a, b, c, d}) {
        some-code
    }
}

但这不起作用

注意:我在询问之前进行了初步搜索,发现的类似问题(Initializing an array in Java using the 'advanced' for each loop [duplicate])不同。

java foreach
1个回答
0
投票

嗯,您每天都会学到一些新东西。显然,您可以初始化数组,但必须定义类型,而不仅仅是使用数组初始化程序。

此作品

        for (String string : new String[] { "a", "b", "c" }) {
            //code
        }

这不起作用,因为它不知道类型。

        for (String string : { "a", "b", "c" }) {
            //code
        }
© www.soinside.com 2019 - 2024. All rights reserved.