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 deprecate a method? Show it with proper example. Plz give the answer of this.Thanx in advance. mail me: tanzeem.akhtar@gmail.com
How u dubugg ur project?
Can private class be inherited in java?
What is a compilation unit?
How to perform Singleton of the java class object on multi JVM?
What is meant by Static query and Dynamic query?
What is a Hash Table? What are the advantages of using a hash table?
what is mena by object block any what is the use of that
In C we use only compiler. Why java uses both compiler and interpreter? What is its significance?
What is class forname used for?
Will the jvm load the package twice at runtime?
How can two threads be made to communicate with each other?