Java Object Clone clone(T array)

Here you can find the source of clone(T array)

Description

Clones the given array object.

License

Apache License

Parameter

Parameter Description
array an array

Return

a clone of the given array

Declaration

public static <T> T clone(T array) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from   w  w w . j a va 2 s  .c  o m*/
     * Clones the given array object. This is useful when the object is known to be an array, but its
     * concrete type (e.g. an array of reference types vs. a {@code byte[]}) is not known.
     *
     * @param array an array
     * @return a clone of the given array
     */
    public static <T> T clone(T array) {
        Class<?> arrayType = array.getClass();
        if (!arrayType.isArray()) {
            throw new IllegalArgumentException("specified object is not an array");
        }
        Class<?> componentType = arrayType.getComponentType();
        Object ret;
        if (!componentType.isPrimitive()) {
            ret = ((Object[]) array).clone();
        } else if (componentType == boolean.class) {
            ret = ((boolean[]) array).clone();
        } else if (componentType == byte.class) {
            ret = ((byte[]) array).clone();
        } else if (componentType == short.class) {
            ret = ((short[]) array).clone();
        } else if (componentType == char.class) {
            ret = ((char[]) array).clone();
        } else if (componentType == int.class) {
            ret = ((int[]) array).clone();
        } else if (componentType == long.class) {
            ret = ((long[]) array).clone();
        } else if (componentType == float.class) {
            ret = ((float[]) array).clone();
        } else if (componentType == double.class) {
            ret = ((double[]) array).clone();
        } else {
            throw new AssertionError("Unrecognized primitive type: " + componentType);
        }
        // We used Object#clone() to create this value, so we know its type is correct
        @SuppressWarnings("unchecked")
        T t = (T) ret;
        return t;
    }
}

Related

  1. clone(E object)
  2. clone(Object a)
  3. clone(Object original)
  4. clone(Object value)
  5. clone(String name, String type, int pos)
  6. clone_obj_array(Object source)
  7. cloneClass(Class clazz)
  8. cloneCloneNotSupportedObject(final T obj, final boolean deep)
  9. cloneShort(Short sOriginal)