/*
 * Written by Josh Bloch and Doug Lea with assistance from members of
 * JCP JSR-166 Expert Group and released to the public domain, as
 * explained at http://creativecommons.org/licenses/publicdomain
 */

import java.util.*;

public class ListSetGet {
    static Random rnd = new Random();
    static int listSize;
    static Class cl;
    static final int ITERS = 100000;

    public static void main(String[] args) {
        listSize = Integer.parseInt(args[1]);
        cl = null;

	try {
	    cl = Class.forName(args[0]);
	} catch(ClassNotFoundException e) {
	    fail("Class " + args[0] + " not found.");
	}

        oneRun();
        oneRun();
        oneRun();
    }

    static void oneRun() {
        long startTime = System.nanoTime();
        int sum = 0;
        List s1 = newList(cl, false);
        AddRandoms(s1, listSize);

        List s2 = newList(cl, false);
        AddRandoms(s2, listSize);

	for (int i = 0; i < ITERS; i++) {
            for (int k = 0; k < listSize; ++k) {
                sum += ((Integer)s1.get(k)).intValue();
                s1.set(k, sum);
            }
        }
	for (int i = 0; i < ITERS; i++) {
            for (int k = 0; k < listSize; ++k) {
                sum -= ((Integer)s2.get(k)).intValue();
                s2.set(k, sum);
            }
        }
	for (int i = 0; i < ITERS; i++) {
            for (int k = 0; k < listSize; ++k) {
                sum += ((Integer)s1.get(k)).intValue();
                sum -= ((Integer)s2.get(k)).intValue();
            }
        }

        if (sum == 0) System.out.print(" ");
        long elapsed = System.nanoTime() - startTime;
        System.out.println("Time: " + (elapsed/1000000000.0) + "s");
    }

    static List newList(Class cl, boolean synch) {
	try {
	    List s = (List)cl.newInstance();
            if (synch)
                s = Collections.synchronizedList(s);
	    if (!s.isEmpty())
		fail("New instance non empty.");
	    return s;
	} catch(Throwable t) {
	    fail("Can't instantiate " + cl + ": " + t);
	}
	return null; //Shut up compiler.
    }

    static void AddRandoms(List s, int n) {
	for (int i=0; i<n; i++) {
	    int r = rnd.nextInt() % n;
	    Integer e = new Integer(r < 0 ? -r : r);

	    int preSize = s.size();
	    if (!s.add(e))
		fail ("Add failed.");
	    int postSize = s.size();
	    if (postSize-preSize != 1)
		fail ("Add didn't increase size by 1.");
	}
    }

    static void fail(String s) {
	System.out.println(s);
	System.exit(1);
    }
}
