Convert a vararg list of items into a List. - Java java.util

Java examples for java.util:List Convert

Description

Convert a vararg list of items into a List.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from  w  w  w  .j  a va  2s .  c o  m*/
     * Convert a vararg list of items into a List. An empty list is returned if items is null
     * 
     * @param <T>
     *            Any type of object
     * @param items
     *            A variable length list of items of type T
     * @return Returns a new ArrayList<T> or an empty list
     */
    public static final <T> List<T> newList(T... items) {
        return addToList(
                new ArrayList<T>(items != null ? items.length : 0), items);
    }


    public static final <T, U extends T> List<T> addToList(List<T> list,
            U... items) {
        if (list != null && items != null) {
            for (int i = 0; i < items.length; i++) {
                list.add(items[i]);
            }
            if (list instanceof ArrayList) {
                ((ArrayList<T>) list).trimToSize();
            }
        }

        return list;
    }

    public static final <T, U extends T> List<T> addToList(List<T> list,
            List<U> items) {
        if (list != null && items != null) {
            list.addAll(items);
        }

        return list;
    }
}

Related Tutorials