[英]Can I iterate over an array defined within a for-loop in Java?
Does Java offer a way to do something like the following without resorting to declaring the array in a separate variable? Java是否提供了一种方法来执行类似下面的操作,而无需在单独的变量中声明数组?
for (String s : {"HEY", "THERE"}) {
// ...
}
The best I can come up with is: 我能想到的最好的是:
for (String s : new ArrayList<String>() {{ add("HEY"); add("THERE"); }}) {
// ...
}
which isn't pretty. 这不漂亮。
Well, the least you can do is this: 嗯,你至少可以这样做:
for (String s : new String[]{"HEY", "THERE"}) {
// ...
}
Since Array
s are "iterable" in Java (although not implementing Iterable
), you could iterate over an Array
instead of an ArrayList
, which could also be in-line initialized. 由于Array
在Java中是“可迭代的”(虽然没有实现Iterable
),你可以迭代一个Array
而不是一个ArrayList
,它也可以在线初始化。
for (String s : Arrays.asList("HEY", "THERE")) {
// ...
}
Not sure why you'd want to do this, but there you have it. 不知道你为什么要这样做,但是你有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.