Can you use array initialization in an enhanced for loop?

Sjors Peterse :

I am trying to improve my code style by writing succinct code. I like Java's enhanced for loop, but I still find that too verbose in the following scenario:

int one = 1;
int two = 2;
int three = 3;

int numbers[] = {one, two ,three};
for (int number : numbers) {
    System.out.println(number);
}

Is it possible to do something like the following?

int one = 1;
int two = 2;
int three = 3;

for (int number : {one, two ,three}) {
    System.out.println(number);
}

In the general case, I have some named variables of the same class that I want to iterate over. Afterwards, I have no use for a array/list of them any more.

Eran :

You can write:

for (int number : new int[] {one, two ,three}) {
    System.out.println(number);
}

You can also use List.of() if you are using Java 9 or above.

for (int number : List.of(one, two ,three)) {
    System.out.println(number);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143301&siteId=1