2

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.

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.