Is it possible to specify an index/range in enhanced for loop in Java?
For e.g. I have a list: List<String> list;
And I want to run a for loop from index 1 instead of 0:
for(String s : list(start from index 1))
OR till index 5
for(String s : list(end at index 5))
I know I can use traditional for loop or keep a counter inside the enhanced for loop but I wanted to know is there something out of the box in Java or apache collections?
4) You don't have access to array index in enhanced for loop, which means you cannot replace the element at giving the index, but for loop provide access to the index, hence allows you to replace any element in the array.
Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.
For a low number of iterations (100-1000), the enhanced for loop seems to be much faster with and without JIT. On the contrary with a high number of iterations (100000000), the traditional loop is much faster.
I would use subList
in this case:
for(String s : list.subList(1, list.size()))
and
for(String s : list.subList(0, 6))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With