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 is a Wrapper class?

14 Answers  


How many types of modifiers are there?

1 Answers   Infosys,


How 'java' got its name and what it stands for?

11 Answers   Wipro,


Why we use methods in java?

0 Answers  


can we take more than one null values for Unique constraints.

1 Answers   3i Infotech,






How many ways can an argument be passed to a subroutine and explain them?

0 Answers  


What is the purpose of using bufferedinputstream and bufferedoutputstream classes?

0 Answers  


Why does java doesnt suuport unsigned values?

0 Answers   ABC,


Why do we use predicate in java?

0 Answers  


Explain the scope or life time of class variables or static variables?

0 Answers  


Define Compiling?

3 Answers  


What super () does in java?

0 Answers  


Categories