Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created September 29, 2014 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/2a53a0444a715f2370cf to your computer and use it in GitHub Desktop.
Save EmmanuelOga/2a53a0444a715f2370cf to your computer and use it in GitHub Desktop.
Custom Array copyOf
import java.lang.reflect.Array;
import java.util.Arrays;
public class Sandbox {
public static Object arrayCopyOf(Object arr, int newLen) {
Class cl = arr.getClass();
if (!cl.isArray()) { return null; }
Class componentType = cl.getComponentType();
int length = Array.getLength(arr);
Object newArray = Array.newInstance(componentType, newLen);
System.arraycopy(arr, 0, newArray, 0, Math.min(length, newLen));
return newArray;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int[] arr2 = (int[]) arrayCopyOf(arr, 3);
int[] arr3 = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr2));
System.out.println(Arrays.toString(arr3));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment