2

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.

sdasdadas
  • 23,917
  • 20
  • 63
  • 148

2 Answers2

5

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.

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118
  • 1
    Nitpick: arrays don't implement the `Iterable` interface. Something different is going on when using enhanced for on them. – Paul Bellora Apr 18 '13 at 00:44
5
for (String s : Arrays.asList("HEY", "THERE")) {
    // ...
}

Not sure why you'd want to do this, but there you have it.

Aurand
  • 5,487
  • 1
  • 25
  • 35
  • 1
    Mostly just curiosity but I learned three things from this question: `Arrays.asList`, `new Object[]{}`, and curiosity has no "u" in it. – sdasdadas Apr 18 '13 at 00:42