Clone a list. - Java java.util

Java examples for java.util:List Operation

Description

Clone a list.

Demo Code


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

import java.util.List;

public class Main {
    /**//from w  w  w  . j a va 2 s.c o m
     * Clone a list.
     * <p>
     * It simply copies the source list to a new {@link #ArrayList}.
     * 
     * @param src - Source list
     * @return the ArrayList with copied values.
     */
    public static <T, M extends List<? extends T>> ArrayList<T> cloneList(
            M src) {
        return copyList(src, new ArrayList<T>());
    }

    /**
     * Copy a list to another one.
     * 
     * @param src - Source list
     * @param dst - Destination list
     * @return the destination list.
     */
    public static <T, M extends List<? extends T>, N extends List<? super T>> N copyList(
            M src, N dst) {
        return copyCollection(src, dst);
    }

    /**
     * Copy a collection to another one.
     * 
     * @param src - Source collection
     * @param dst - Destination collection
     * @return the destination collection.
     */
    public static <T, M extends Collection<? extends T>, N extends Collection<? super T>> N copyCollection(
            M src, N dst) {
        synchronized (src) {
            synchronized (dst) {
                dst.clear();

                for (T element : src)
                    dst.add(element);

                return dst;
            }
        }
    }
}

Related Tutorials