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
How a string is stored in memory?
What does || || mean in math?
Difference between process and thread?
I want to print “hello” even before main is executed. How will you acheive that?
Explain the available thread states in a high-level?
Explain the private field modifier?
What is the method to expand and collapse nodes in a jtree?
What is lifetime variable?
What is thread pool in java with example?
How do you add spaces in java?
What is volatile keyword in java
Why is boolean important?
Which is better ascii or unicode?
Does a class inherit the constructors of its superclass in java programming?
What is difference between classpath and path variables in java?