0

In some languages, Python, for example, one could directly iterate through an array:

for i in [1, 2, 3, 4]: print(i) 

I know Java can iterate through a variable by for (type var : var2), then is it possible to skip the variable and directly iterate an array? such as:

for (int i : [1, 2, 3, 4]) { System.out.println(i); } 
9
  • What is [1, 2, 3, 4] supposed to be? There are no list literals in Java. Commented Aug 28, 2019 at 20:31
  • 10
    for (int i : new int[] {1, 2, 3, 4}) Commented Aug 28, 2019 at 20:31
  • @LutzHorn An array. In this case an array of integers. I use [1, 2, 3, 4] just as a demo. Commented Aug 28, 2019 at 20:32
  • 2
    I don't quite understand. The question is what you want to say. What is your question? Commented Aug 28, 2019 at 20:35
  • 1
    @LutzHorn Jocob solved it, I want to iterate through an array without having to create a variable. Commented Aug 28, 2019 at 20:37

3 Answers 3

2

I want to iterate through an array without having to create a variable.

You need change the loop to this:

for (int i : new int[] {1, 2, 3, 4}) { // do something (4 iterations) } 

Credit: Jacob G.

Sign up to request clarification or add additional context in comments.

Comments

2

If you really want to avoid using bracket syntax you can also do:

for (int i : Arrays.asList(1,2,3,4)) { System.out.println(i); } 

Which will effectively do the same thing as creating an Array, but instead you are iterating on a fixed size List.

Note: This answer is mainly just for knowledge, and in practice you should not do this and prefer using new int[]{} over importing the Arrays library and boxing the values as a List unnecessarily.

The more traditional way you might see asList() used would be similar to:

Arrays.asList(1,2,3,4).forEach(System.out::println); 

3 Comments

That it is fixed size is irrelevant, because you couldn't do anything to change its size even if it weren't (e.g. for (int i : new ArrayList<>(Arrays.asList(1,2,3,4))) {. Also, note that this is boxing the values, only to immediately unbox them again.
@Andy Turner I don't recommend doing it this way, I just put it as alternative if he really insists of iterating in a way that looks similar to Python. It is nice to learn alternatives exist even if they are not good ones, in my opinion.
@Andy Turner Will do.
1

You could, of course create the following utility:

class ArrayUtils { static int[] of(int... array) { return array; } } 

And then static-import this method, using import static ArrayUtils.of. Now you have a rather short expression:

for (int i : of(1, 2, 3, 4)) { ... } 

I wouldn't, however, do this in a real-life scenario. I would instead just write an ol' skool

for (int i = 1; i <= 4; i++) { ... } 

or maybe

IntStream.rangeClosed(1, 4) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.