Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

For-each loop vs. Iterator Handout Example of a for-each loop public class TestForEach public static void main(String [ J args) int [ J arr (1,

image text in transcribed
image text in transcribed
For-each loop vs. Iterator Handout Example of a for-each loop public class TestForEach public static void main(String [ J args) int [ J arr (1, 2, 3, 4,5,6, 7, 8) for (int i arr)//i is NOT an index: it's the value in a particular location // i holds the value of the current iteration's element arrli]- 0: for (int i: arr) System.out.printin(i): //variable i takes values in the array, one at a time, not an array index Eirst iteration (look at the first number) Second iteration (look at the second number) Third iteration (look at the third number) Fourth iteration (look at the fourth number) Fifth iteration (look at the fifth number) Sixth iteration (look at the sixth number) Seventh iteration (look at the seventh number) Eighth iteration (look at the eighth number) For-each loop is useful when you need only the values of the array. Do NOT use a for-each: If you need to change the contents of an array element: might not change it correctly If you need to access sOME of the array elements, but not all of them If you need to work through the array elements in reverse order If you need to simultaneously work with two or more arrays within a loop If you need to refer to the index of a particular element - - - - - If any of these cases apply, then use a regular for loop for-each (definite iteration)- recall: compiler generates the iterator calls for you Process EVERY element WITHOUT removing an element Trying to remove() during an iteration causes a ConcurrentModificationException - - Iterator object (indefinite iteration) Use if you want to stop part way through Used with collections where indexed access is inefficient or impossible Used to remove an object from a collection during iteration and possibly change the element at that position Available for all collections Using an iterator, we don't need to know how the data structure (collection) is implemented

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Programming With Visual Basic .NET

Authors: Carsten Thomsen

2nd Edition

1590590325, 978-1590590324

More Books

Students also viewed these Databases questions

Question

10. Describe the relationship between communication and power.

Answered: 1 week ago