Java:for-each-loop 中的“匿名”数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2358866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:32:22  来源:igfitidea点击:

Java: "Anonymous" array in for-each-loop

javaarraysforeach

提问by Atmocreations

While I was trying something special in for loop I recognized that Java doesn't seem to like putting an anonymous array right as the source for a for-each-loop:

当我在 for 循环中尝试一些特殊的东西时,我意识到 Java 似乎不喜欢将匿名数组作为 for-each-loop 的源:

for (String crt : {"a","b","c"} ) {
    doSomething();
}

actually doesn't work while

实际上不起作用,而

String[] arr = {"a","b","c"};
for (String crt : arr ) {
    doSomething();
}

does.

做。

Even casting the array to String[] doesn't help. When moving the cursor over the first version, eclipse tells me:

即使将数组转换为 String[] 也无济于事。将光标移到第一个版本上时,eclipse 告诉我:

Type mismatch: cannot convert from String[] to Stringwhile meaning "crt".

Type mismatch: cannot convert from String[] to String而意思是“crt”。

Is this a bug?

这是一个错误吗?

采纳答案by noah

This will work:

这将起作用:

for (String crt : new String[]{"a","b","c"} ) {
    doSomething();
}

回答by Chris Dennett

Dunno, what about this? :) Pity there's no succinct version. Suppose you could use Groovy or Scala if you wanted anything like that :)

不知道,这个怎么办?:) 可惜没有简洁的版本。假设你可以使用 Groovy 或 Scala,如果你想要这样的东西:)

for (String s : Arrays.asList("a","b","c")) {
    hmm(s);
}

回答by dbrown0708

You want

你要

for (String crt : new String [] {"a","b","c"} ) {
    doSomething();
}

I use IntelliJ and it says put the message "expression expected" on the right-hand side of the colon in the for-loop, which seems more accurate.

我使用 IntelliJ,它说​​在 for 循环的冒号右侧放置“预期表达式”消息,这似乎更准确。

I should add that IntelliJ also offers to add the "new String []" automagically for me.

我应该补充一点,IntelliJ 还提供为我自动添加“新字符串 []”。

回答by Tom Castle

The Java language provides the {"a","b","c"}form as a shortcut, but it is only possible during assignment. It's possible this is to avoid possible ambiguities during parsing, in some positions {}could be interpreted as a code block.

Java 语言提供了{"a","b","c"}表单作为快捷方式,但只能在赋值期间使用。这可能是为了避免解析过程中可能出现的歧义,在某些位置{}可以解释为代码块。

The right way to do it would be how noah suggests, with new String[]{"a","b","c"}.

正确的方法是诺亚建议的,使用new String[]{"a","b","c"}.