Java examples for java.util:Collection to Array
Returns a defensive copy for either Collections, Maps or Arrays
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; public class Main{ public static void main(String[] argv){ Object object = "java2s.com"; System.out.println(defensiveCopy(object)); }//from w w w . j a va 2 s . c o m /** * Returns a defensive copy for either Collections, Maps or Arrays */ @SuppressWarnings("unchecked") public static <T> T defensiveCopy(final Object object) { if (object == null) { return null; } else if (object instanceof Set) { return (T) new LinkedHashSet<Object>((Set<?>) object); } else if (object instanceof Collection) { return (T) new ArrayList<Object>((Collection<?>) object); } else if (object instanceof Properties) { final Properties properties = new SortedProperties(); properties.putAll((Properties) object); return (T) properties; } else if (object instanceof Map<?, ?>) { return (T) new LinkedHashMap<Object, Object>((Map<?, ?>) object); } else if (object.getClass().isArray()) { final int length = Array.getLength(object); final Object newArray = Array.newInstance(object.getClass() .getComponentType(), length); System.arraycopy(object, 0, newArray, 0, length); return (T) newArray; } else { return (T) object; } } }