Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(final String[] args) {
        Map<String, String> items;

        items = new HashMap<String, String>();
        items.put("A", "1");
        items.put("B", "2");
        items.put("C", "3");

        display(new RandomIterator<String>(items.keySet().iterator()));
        display(new RandomIterator<String>(items.keySet().iterator()));
    }

    private static <T> void display(final Iterator<T> iterator) {
        while (iterator.hasNext()) {
            final T item;
            item = iterator.next();
            System.out.println(item);
        }
    }
}

class RandomIterator<T> implements Iterator<T> {
    private final Iterator<T> iterator;

    public RandomIterator(final Iterator<T> i) {
        final List<T> items;

        items = new ArrayList<T>();

        while (i.hasNext()) {
            final T item;

            item = i.next();
            items.add(item);
        }

        Collections.shuffle(items);
        iterator = items.iterator();
    }

    public boolean hasNext() {
        return (iterator.hasNext());
    }

    public T next() {
        return (iterator.next());
    }

    public void remove() {
        iterator.remove();
    }
}