Can we iterate through collection using for loop?

Answers were Sorted based on User's Feedback



Can we iterate through collection using for loop?..

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

Can we iterate through collection using for loop?..

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

Post New Answer

More Core Java Interview Questions

Why java applets are more useful for intranets as compared to internet?

0 Answers  


What do you mean by an object in java?

0 Answers  


How do you print array in java?

0 Answers  


What does indexof return in java?

0 Answers  


Need 2+ yrs experienced java techinical question papaer for company Iflex

1 Answers   TCS,


Should database connections be singleton?

0 Answers  


how many ways we can serialize the java object?

2 Answers   Satyam,


Does treeset use compareto?

0 Answers  


What is the difference(or similarity if there are some) between object and a variable?

4 Answers   ME,


what is the difference between statis block and static variable

7 Answers  


how many design pattern r there? and wht design pattern u use and why ?

5 Answers   HP,


What is the alternate of 'Inheritance' ?

4 Answers   CybAge, HCL,


Categories