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.
Well, the least you can do is this:
for (String s : new String[]{"HEY", "THERE"}) {
// ...
}
Since Arrays 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With