Reputation: 25106
Does Java offer a way to do something like the following without resorting to declaring the array in a separate variable?
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.
Upvotes: 2
Views: 85
Reputation: 27200
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.
Upvotes: 5
Reputation: 5537
for (String s : Arrays.asList("HEY", "THERE")) {
// ...
}
Not sure why you'd want to do this, but there you have it.
Upvotes: 5