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
Considering notepad/ie or any other thing as process, what will happen if you start notepad or ie 3 times? Where 3 processes are started or 3 threads are started?
What is methods and methodology?
Write a code to show a static variable?
How do you use compareto in java?
Is array dynamic in java?
What are the properties of thread?
How do you reverse sort a list in java?
What is a conditional statement explain with example?
What are the types of relation?
What is the current version of java?
What are the different data types in java?
What is public/private protected in java?
What is the difference between the final method and abstract method?
Why static functions are used?
What is boolean query?