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

Give a brief description of java socket programming?

724


Where are the local variables stored?

716


Write a code to create a trigger to call a stored procedure

720


What is queue in java?

769


Why do we need autoboxing in java?

735


Explain what is encapsulation?

799


Is char a data type in java?

728


What is methods and methodology?

758


What is difference between iterator access and index access?

833


These static constructors are correct ? class A { statc intA() { } static A(int x,int y) { } static A(int x) { } }

789


What is thread safe singleton?

700


What are the main differences between notify and notifyAll in Java?

805


Why are lists ordered in java?

753


Explain about assignment statement?

781


How many bits are used to represent unicode, ascii, utf-16, and utf-8 characters?

802