sdasdadas
sdasdadas

Reputation: 25106

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.

Upvotes: 2

Views: 85

Answers (2)

zw324
zw324

Reputation: 27200

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.

Upvotes: 5

Aurand
Aurand

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

Related Questions