Java Object Clone copyIfNecessary(final Object val)

Here you can find the source of copyIfNecessary(final Object val)

Description

copy If Necessary

License

BSD License

Declaration

@SuppressWarnings("unchecked")
    private static Object copyIfNecessary(final Object val) 

Method Source Code

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

import java.util.*;

public class Main {
    @SuppressWarnings("unchecked")
    private static Object copyIfNecessary(final Object val) {
        if (val instanceof Map) {
            return deepCopy((Map<String, ?>) val);
        } else if (val instanceof List) {
            return deepCopy((List<?>) val);
        } else {/*from  ww w  .j ava2  s .  c  o  m*/
            return val;
        }
    }

    /**
     * Performs deep (recursive) copy of PlanOut script parse tree (represented by combination of maps and lists).
     * @param script the "tree" to copy
     * @return Map representing the newly created copy
     */
    public static Map<String, ?> deepCopy(final Map<String, ?> script) {
        // the copy can possibly grow by 1 entry due to "salt" key being added,
        // hence the small optimization with capacity and load factor
        final Map<String, Object> copy = new LinkedHashMap<>(
                script.size() + 1, 1);
        for (String key : script.keySet()) {
            copy.put(key, copyIfNecessary(script.get(key)));
        }
        return copy;
    }

    private static List<?> deepCopy(final List<?> list) {
        final List<Object> copy = new ArrayList<>(list.size());
        for (Object val : list) {
            copy.add(copyIfNecessary(val));
        }
        return copy;
    }
}

Related

  1. clone_obj_array(Object source)
  2. cloneClass(Class clazz)
  3. cloneCloneNotSupportedObject(final T obj, final boolean deep)
  4. cloneShort(Short sOriginal)
  5. cloneStackTrace(Throwable aException)