Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;
import java.util.Collection;

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

public class Main {
    /**
     * Iterates over a set of elements and creates a List that contains all of them.  The order of the elements in
     * the List will be the order returned by <code>iterator</code> parameter.
     * @param <T> The type of element iterated over.
     * @param iterator The set of elements to iterate over
     * @return A new Collection that contains all the elements returned by the iterator.
     */
    public static <T> List<T> toList(Iterator<T> iterator) {
        List<T> newList = new ArrayList();
        addToCollection(newList, iterator);
        return newList;
    }

    /**
     * Adds the contents of an iterator to an existing Collection.
     * @param <T> The type of elements returned by the iterator.
     * @param collection The receptacle to put the elements into.
     * @param elementsToAdd The elements to add to the Collection.
     */
    public static <T> void addToCollection(Collection<T> collection, Iterator<T> elementsToAdd) {
        while (elementsToAdd.hasNext()) {
            T next = elementsToAdd.next();
            collection.add(next);
        }
    }
}