Can we iterate through collection using for loop?
Answers were Sorted based on User's Feedback
Answer / 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 |
Answer / haneef
Yes, We can
Set set=new HashSet();
set.add("one");
set.add("two");
for(Iterator it=set.iterator();it.hasNext();)
{
System.out.println(it.next());
}
Is This Answer Correct ? | 3 Yes | 1 No |
How to Create A Wapper Class in core Java and Why are Use in java?
What is the purpose of static keyword in java?
Every class extends object but why it is not possible for every object to invoke clone() method. ideally protected methods should be accessible from sub classes. isn't it?
Is arraylist a class in java?
Is sizeof a keyword in java programming?
What is the base class of all exception classes in java?
What is jit and its use?
What does flagged out mean?
The class "Class" is belongs to which package?? a) java.lang b)java.lang.reflect c)java.util d)None
Which is fastest collection in java?
What are the high-level thread states in java programming?
What is the common usage of serialization?