0 votes
1 view
in Java by (3.4k points)

Consider:

List<String> someList = new ArrayList<String>();

// add "Lion", "Cow", "key" to someList

for (String item : someList) 

{

What would the equivalent for loop look like without using the for each syntax?

1 Answer

0 votes
by (46.1k points)

for (Iterator<String> i = someIterable.iterator(); i.hasNext();) 

{

    String item = i.next();

    System.out.println(item);

}

Note that if you require to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

The code above works for any object that implements the Iterable interface.

Also, if the right-hand side of the for ( : ) expression is an array rather than an Iterable element, the internal code practices an int index counter and checks on array.length instead. See this to know more.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 30, 2019 in Java by Krishna (2.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...