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

Give an example of use of pointers in java class.

0 Answers  


which method throws exception of type Throwable

2 Answers  


Is upper case in java?

0 Answers  


Difference between a Scrollbar and a ScrollPane?

1 Answers  


what is connection pooling with example?

3 Answers   Amdocs,


Is it necessary for the port addresses to be unique? Explain with reason.

0 Answers   Aricent,


I don’t want my class to be inherited by any other class. What should I do?

0 Answers  


if the memory capacity is 700 presently occupied by process is 690. then another process request space(40) how this situation handled in java.

4 Answers   Wipro,


How hashmap works in java?

0 Answers  


Why map is used in java?

0 Answers  


What is the difference between length and size in java?

0 Answers  


What is difference between string and new string?

0 Answers  


Categories