sheenareid
sheenareid

Reputation: 21

Can you use an enhanced for each loop to add elements to an array?

I know you cannot use an enhanced for loop to change the array elements, but what about adding things into an array?

Many thanks

Upvotes: 0

Views: 424

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

You can never "add" an element to an array. It is a fixed-size data structure, with or without an enhanced for loop. All you can do is to allocate an array, and then set its elements.

It doesn't make sense to allocate the array you are iterating in the enhanced for loop - what then are you iterating? - and as you have stated in the question, you cannot set array elements (directly) in a for loop.

So, no.

Upvotes: 1

Related Questions