Generic method to do array Clone - Java Collection Framework

Java examples for Collection Framework:Array Clone

Description

Generic method to do array Clone

Demo Code

/*/*w  w w  . j  a v a  2  s .  c  om*/
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */
//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T[] arrayClone(T[] array) {
        if (array == null) {
            return array;
        }
        if (array.length == 0) {
            return (T[]) Array.newInstance(array.getClass()
                    .getComponentType(), 0);
        }

        T[] clonedArray = (T[]) Array.newInstance(array[0].getClass(),
                array.length);
        System.arraycopy(array, 0, clonedArray, 0, array.length);

        return clonedArray;
    }
}

Related Tutorials