Simon Kuang
Simon Kuang

Reputation: 3940

Inline Array Definition in Java

Sometimes I wish I could do this in Java:

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

Unfortunately, I have to do something like this instead:

int [] i = {1, 2, 3, 4, 5};
// ...

My recollection is that C++ has this sort of feature. Is there an OOP replacement for inline array definitions (maybe even to the point of instantiating anonymous classes)?

Upvotes: 1

Views: 6005

Answers (3)

ktm5124
ktm5124

Reputation: 12123

You could create the int[] array in the for loop.

for (int i : new int[] {1, 2, 3, 4, 5}) {
   ...
}

Here you are making an anonymous int array, which is the closest thing to what you want. You could also loop through a Collection.

Note that this question has nothing to do with OOP. It's merely a matter of syntax. Java supports anonymous arrays/objects just like C++.

Upvotes: 4

rgettman
rgettman

Reputation: 178313

You don't have to create a separate variable for this. The syntax {1, 2, ...} is valid only for declarations, but you can always say new int[] {1, 2, ...}:

for (int i : new int[] {1, 2, 3, 4, 5})

Upvotes: 3

MAV
MAV

Reputation: 7457

I think the closest you are gonna get is:

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

Upvotes: 7

Related Questions