/*
 * ForLoopTest.java
 *
 * Created on June 9, 2004, 11:04 AM
 */

import java.util.ArrayList;
import java.util.Iterator;
/**
 * Examples of the new for loop for use with collections and arrays
 * @author  cpresser
 */
public class ForLoopTest {
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double[] array =  {2.5, 5.2, 7.9, 4.3, 2.0, 4.1, 7.3, 0.1, 2.6};
        
        //leave details of the loop such as indices out of the picture
        //simple forward iteration of the loop
        for(double d: array){
            System.out.println(d);
        }
        System.out.println("---------------------");
        
        //this works with anything that implements the Iterable interface
        //This includes Collections like ArrayList
        // We'll use generics to create an ArrayList of Integer variables
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(7);
        list.add(15);
        list.add(-67);
        for(Integer number: list){
            System.out.println(number);
        }
        System.out.println("---------------------");
        //and of course it works identically with autounboxing
        for(int item: list){
            System.out.println(item);
        }
        
        System.out.println("---------------------");
        //you can also make your own Iterable classes (see below)
        //In this case we are swatting a fly with a sledgehammer.
        MyIterableClass series = new MyIterableClass();
        for(double d: series){
            System.out.println(d);
        }
    }
    
}


//sending the type to iterable allows us to use the loop
//    for(double d: list) or for(Double d: list)
//              instead of
//    for(Object o: list)
class MyIterableClass implements Iterable<Double>, Iterator<Double>{
    static final double CLOSE_TO_ZERO = 0.0001;
    double value;
    double factor = -0.5;
    
    public MyIterableClass(){
        value = 1.0;
    }
    
    //iterable method
    public Iterator<Double> iterator(){
        return this;
    }
    
    //iterator methods
    public boolean hasNext(){
        return !(value > -CLOSE_TO_ZERO && value < CLOSE_TO_ZERO);
    }
    
    public Double next(){
        double result = value;
        value = value*factor;
        return result;
    }
    
    public void remove(){
        //this list is generated, so there is no removing from it        
        throw new UnsupportedOperationException("There is nothing to remove");  
    }
    
}