Can we iterate through collection using for loop?

Answer Posted / qim2010

Yes.


/*
Iterate through a Collection using Java Iterator Example

This Java Example shows how to iterate through a Collection
using Java Iterator.

*/
import java.util.Iterator;
import java.util.ArrayList;

public class JavaIteratorExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList aList = new ArrayList();

//populate ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");

/*
Get Iterator object by invoking iterator method of
collection.
Iterator provides hasNext() method which returns
true if has more
elements. next() method returns the element in
iteration.
*/

//iterate through the ArrayList values using
Iterator's hasNext and next methods
for (Iterator itr = aList.iterator(); itr.hasNext();) {
//while(itr.hasNext())
System.out.println(itr.next());
/*
Please note that next method may throw a
java.util.NoSuchElementException
if iteration has no more elements.
*/
}
}
}

Is This Answer Correct ?    3 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

what is the messsage u r going to get from an objectoriented programing?

1609


Can we override compareto method?

498


What is methods and methodology?

529


design an lru cache in java?

542


How to implement an arraylist in java?

505






When does an object becomes eligible for garbage collection in java?

573


What must a class do to implement an interface in java programming?

533


What are the three parts of a lambda expression?

532


How to do a true java ping from windows?

612


What is a java developer salary?

542


What is the java reflection api? Why it’s so important to have?

550


What is a conditional equation?

558


How does system arraycopy work in java?

577


What is anagram in java?

516


How does compareto method work?

522