Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 472
sdasdadas Avatar asked Dec 02 '25 06:12

sdasdadas


1 Answers

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.

like image 84
zw324 Avatar answered Dec 03 '25 20:12

zw324



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!