Java List Create asList(Collection items)

Here you can find the source of asList(Collection items)

Description

as List

License

Open Source License

Declaration

public static <T> List<T> asList(Collection<T> items) 

Method Source Code

//package com.java2s;
/**//from   w w  w .  j a  va 2 s. c o  m
 * Copyright 2013-2014 Guoqiang Chen, Shanghai, China. All rights reserved.
 *
 * Email: subchen@gmail.com
 * URL: http://subchen.github.io/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    public static <T> List<T> asList(T[] items) {
        if (items == null) {
            return null;
        }
        return Arrays.asList(items);
    }

    public static <T> List<T> asList(Collection<T> items) {
        if (items == null) {
            return null;
        }
        if (items instanceof List) {
            return (List<T>) items;
        }
        return new ArrayList<T>(items);
    }

    public static <T> List<T> asList(Iterator<T> items) {
        if (items == null) {
            return null;
        }
        List<T> results = new ArrayList<T>();
        while (items.hasNext()) {
            results.add(items.next());
        }
        return results;
    }

    public static <T> List<T> asList(Iterable<T> items) {
        if (items == null) {
            return null;
        }
        if (items instanceof List) {
            return (List<T>) items;
        } else if (items instanceof Collection) {
            return new ArrayList<T>((Collection<T>) items);
        } else {
            return asList(items.iterator());
        }
    }

    public static <T> List<T> asList(Enumeration<T> items) {
        if (items == null) {
            return null;
        }
        List<T> results = new ArrayList<T>();
        while (items.hasMoreElements()) {
            results.add(items.nextElement());
        }
        return results;
    }
}

Related

  1. asList(E... elements)
  2. asList(E[] array)
  3. asList(final int... values)
  4. asList(final Iterator data)