/*
 * [TestIteratorRemove.java]
 *
 * Summary: example use of Iterator.remove.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2009-08-08 initial version
 */
package com.mindprod.example;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import static java.lang.System.*;

/**
 * example use of Iterator.remove.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2009-08-08 initial version
 * @since 2009-08-08
 */
public final class TestIteratorRemove
    {
    /**
     * how many items we store in the arrayList
     */
    private static final int MAX_ITEMS = 25;

    /**
     * Sample code to TestIterable. Needs JDK 1.8+
     *
     * @param args not used
     */
    public static void main( String[] args )
        {
        // intitialise ArrayList with some random numbers.
        ArrayList<Integer> items = new ArrayList<>( MAX_ITEMS );
        Random wheel = new Random();
        for ( int i = 0; i < MAX_ITEMS; i++ )
            {
            items.add( wheel.nextInt() );
            }
        // I T E R A T O R - R E M O V E :  efficiently removing elements from a List (ArrayList, LinkedList etc.)
        // or Collection.
        // You can't remove elements with a for:each.
        // This works faster than a get/remove.
        // This approach avoids the effects of the List renumbering as you go which can cause you to
        // inadvertently skip elements or run off the end.
        for ( Iterator<Integer> iter = items.iterator(); iter.hasNext(); )
            {
            // auto/unboxing
            int item = iter.next();
            if ( ( item & 1 ) == 0 )
                {
                // remove even numbers from from underlying ArrayList
                iter.remove();
                }
            }
        // should just have odd numbers left
        for ( Integer i : items )
            {
            out.println( i );
            }
        } // end main
    }