Created
September 29, 2014 03:54
-
-
Save EmmanuelOga/2a53a0444a715f2370cf to your computer and use it in GitHub Desktop.
Custom Array copyOf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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