英文:
Is it possible to initialise an array in the for each loop's condition area?
问题
在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
}
}
但是这样是行不通的。
注意:在提问之前,我进行了初步的搜索,我找到的类似问题(使用'高级'for each循环初始化Java中的数组)与此不同。
英文:
In python, you can do this:
for item in [a, b, c, d]:
some-code
Is something similar possible in java, where you declare the array in the for loop condition area?
My gut reaction is to do this:
public static void main(String[] args) {
for (String string : String myArr[] = {a, b, c, d}) {
some-code
}
}
But that does not work
Note: I did a preliminary search before asking, the similar-seeming question I found (Initializing an array in Java using the 'advanced' for each loop [duplicate]) is different.
答案1
得分: 1
好的,以下是翻译好的内容:
每天都会学到新东西。显然,你可以初始化一个数组,但你必须定义类型,而不能仅使用数组初始化器。
这个有效:
for (String string : new String[] { "a", "b", "c" }) {
//代码
}
这个无效,因为它不知道类型:
for (String string : { "a", "b", "c" }) {
//代码
}
英文:
Well, you learn something new everyday. Apparently you can initialize an array but you must define the type and not just use an array initializer.
This works
for (String string : new String[] { "a", "b", "c" }) {
//code
}
This doesn't work because it's unaware of type.
for (String string : { "a", "b", "c" }) {
//code
}
答案2
得分: 0
你可以直接使用Java中的Arrays.asList()
方法调用来初始化数组。示例代码如下:
for(String data: Arrays.asList("a","b","c")){
// 这里放置代码
}
英文:
You can directly initialize array with the help of Arrays.asList()
method call in java.
A sample code snippet is shown as follows:
for(String data: Arrays.asList("a","b","c"){
// code here
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论