Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

Can we iterate through collection using for loop?

Answer Posted / 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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is protected access modifier?

962


Difference between this() and super() in java ?

1034


how are methods defined?

1000


What is final modifier?

995


How does singleton class work?

939


Which of the following is not an isolation level in the JDBC

2082


How many types of interfaces are there?

991


What do you mean by stream pipelining in java 8?

1164


What is double checked locking in singleton?

1010


Is string is a data type in java?

993


Can we use catch statement for checked exceptions when there is no chance of raising exception in our code?

987


How many types of assembly languages are there?

925


What is the difference between @before and @beforeclass annotation?

1028


Explain the difference between string, stringbuffer and stringbuilder in java?

964


What's the base class of all exception classes?

1019