Creates a list that contains all elements of argument elements repeated amount times. - Java Collection Framework

Java examples for Collection Framework:List

Description

Creates a list that contains all elements of argument elements repeated amount times.

Demo Code


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main{
    /**/*from  w  w  w  . j  av a2 s  . co  m*/
     * Creates a list that contains all elements of argument elements repeated
     * amount times.
     *
     * @param <T> Type of the elements.
     * @param amount Tells how often the input elements are added to the list.
     * @param elements The elements to add to the list.
     *
     * @return The created list that contains the input elements.
     */
    public static <T> List<T> repeat(final int amount, final T... elements) {
        if (amount <= 0) {
            throw new IllegalArgumentException(
                    "Error: Amount argument must be positive");
        }

        final List<T> list = new ArrayList<T>();

        for (int i = 0; i < amount; i++) {
            list.addAll(ListHelpers.list(elements));
        }

        return list;
    }
    /**
     * Creates a list by taking an input list and adding elements to the list.
     *
     * @param <T> Type of the list.
     * @param list The input list.
     * @param elems The elements to add to the list.
     *
     * @return The modified input list.
     */
    public static <T> List<T> list(final List<T> list, final T... elems) {
        for (final T elem : elems) {
            list.add(elem);
        }

        return list;
    }
    /**
     * Creates a list from a number of elements.
     *
     * @param <T> The type of the elements.
     * @param elems The elements to add to the list.
     *
     * @return The list that contains the input elements.
     */
    public static <T> List<T> list(final T... elems) {
        final List<T> list = new ArrayList<T>();

        for (final T elem : elems) {
            list.add(elem);
        }

        return list;
    }
}

Related Tutorials