创建一个列表,其中包含参数元素的所有元素重复次数。
import java.util.ArrayList; import java.util.Collection; import java.util.List; /** N o w J a v a . c o m 提供 **/ public class Main{ /** * 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"); } /* n o w j a v a . c o m - 时代Java 提 供 */ 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. */