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
What is protected access modifier?
Difference between this() and super() in java ?
how are methods defined?
What is final modifier?
How does singleton class work?
Which of the following is not an isolation level in the JDBC
How many types of interfaces are there?
What do you mean by stream pipelining in java 8?
What is double checked locking in singleton?
Is string is a data type in java?
Can we use catch statement for checked exceptions when there is no chance of raising exception in our code?
How many types of assembly languages are there?
What is the difference between @before and @beforeclass annotation?
Explain the difference between string, stringbuffer and stringbuilder in java?
What's the base class of all exception classes?