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

What are the similarities between an array and an ArrayList?

3 Answers  


Difference between canvas class & graphics class?

1 Answers  


If you do not want your class to be inherited by any other class. What would you do?

0 Answers  


What are locale settings?

0 Answers  


What is runtime polymorphism or dynamic method dispatch?

0 Answers  






interface X{ void m1(); void m2(); } class Child2 extends Object implements X { public void m1(){ System.out.println("Child2 M1"); } public void m2(){ System.out.println("Child2 M2"); } } public class ParentChildInfterfaceDemo { public static void main(String[] args){ X x = new Child2(); X x1 = new Child2(); x.m1(); x.m2(); x.equals(x1); } } Will the above code work? If yes? Can you please explain why the code x.equals(x1) will work as the equals method is called on interface reference vaiable?

2 Answers  


Is node a data type in java?

0 Answers  


Is set thread safe java?

0 Answers  


What is difference between hash mapping and hash table?

5 Answers   NDS, Wipro,


What is this keyword used for?

0 Answers  


what is tempplate pattern

4 Answers   IBM, RBS,


Which access specifier can be used with class ?

0 Answers  


Categories