Switch to full style
Java Collections classes examples .
Post a reply

iterator on list

Sun Oct 21, 2012 12:28 pm

Iterator on java list
Code:

import java
.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        List<Float> floatList = new ArrayList<Float>();
        for (float num = 0; num < 1; num+=0.05) {
            floatList.add(num);
        }
        Iterator listIterator = floatList.iterator();
        while (listIterator.hasNext()) // check if it has next
        {
            System.out.println(listIterator.next());
        }
    }
 

}
 


the output is :
Code:

0.0
0.05
0.1
0.15
0.2
0.25
0.3
0.35000002
0.40000004
0.45000005
0.50000006
0.5500001
0.6000001
0.6500001
0.7000001
0.7500001
0.80000013
0.85000014
0.90000015
0.95000017


You can also fill the list using random class:
Code:

      List
<Float> floatList = new ArrayList<Float>();
        for (float num = 0; num < 1; num+=0.05) {
            floatList.add(new Random().nextFloat()*num);
        }
        Iterator listIterator = floatList.iterator();
        while (listIterator.hasNext()) // check if it has next
        {
            System.out.println(listIterator.next());
        }
 


You can use for loop (for keyword) with iterator like this:
Code:

  Iterator listIterator 
= floatList.iterator();
        for (;listIterator.hasNext();) // check if it has next
        {
            System.out.println(listIterator.next());
        }
 


You can work on element by element like this (with generic data type added to the iterator):
Code:

      Iterator
<FloatlistIterator floatList.iterator();
        while (
listIterator.hasNext()) // check if it has next
        
{
            
Float fnum=  listIterator.next();
            
fnum+=0.1f;
            
System.out.println(fnum);
        }
 




Post a reply
  Related Posts  to : iterator on list
 Removing elements from array list with the iterator     -  
 Iterator interface     -  
 Iterator on Vector     -  
 Implementation of List     -  
 List all database in php     -  
 List C++ implementation     -  
 Sort a list     -  
 list and explode     -  
 display list     -  
 reverse list     -  

Topic Tags

Java Collections