View RSS Feed

Advanced Java

Iterating a Collection

Rate this Entry
by , 02-18-2012 at 04:07 PM (1424 Views)
Collection’s all elements are iteration is done by getting an iterator from collection. Use the iterator through collection.

It is explained by this given code:
Java Code: This is the code to explain the collection iteration
Collection myCollection = new HashSet();
//... add elements to the collection

Iterator iterator = myCollection.iterator();
while(iterator.hasNext()){
    Object object = iterator.next();
    //do something to object;    
}

//You can also use the new for-loop: 

Collection myCollection = new HashSet();
//... add elements to the collection

for(Object object : collection) {
  //do something to object;
}

Submit "Iterating a Collection" to Facebook Submit "Iterating a Collection" to Digg Submit "Iterating a Collection" to del.icio.us Submit "Iterating a Collection" to StumbleUpon Submit "Iterating a Collection" to Google

Categories
Collection

Comments