/** * Reallocates an array with a new size, and copies the contents of the old array to the new * array. * * @param oldArray the old array, to be reallocated. * @param newSize the new array size. * @return A new array with the same contents. */ public static Object resizeArray(Object oldArray, int newSize) { int oldSize = java.lang.reflect.Array.getLength(oldArray); @SuppressWarnings("rawtypes") Class elementType = oldArray.getClass().getComponentType(); Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize); int preserveLength = Math.min(oldSize, newSize); if (preserveLength > 0) System.arraycopy(oldArray, 0, newArray, 0, preserveLength); return newArray; }
// from // http://stackoverflow.com/questions/5606338/cast-primitive-type-array-into-object-array-in-java private static Object[] toObjectArray(Object val) { if (val instanceof Object[]) return (Object[]) val; int arrayLength = java.lang.reflect.Array.getLength(val); Object[] outputArray = new Object[arrayLength]; for (int i = 0; i < arrayLength; ++i) { outputArray[i] = java.lang.reflect.Array.get(val, i); } return outputArray; }
// math behide resizeArray. private Object resizeArray(Object oldArray, int newSize) { // This class was taken directly from "http://www.source-code.biz/snippets/java/3.htm" // You try to dynamically resizing an array, than come talk to me about coping code. int oldSize = java.lang.reflect.Array.getLength(oldArray); Class elementType = oldArray.getClass().getComponentType(); Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize); int preserveLength = Math.min(oldSize, newSize); if (preserveLength > 0) { System.arraycopy(oldArray, 0, newArray, 0, preserveLength); } return newArray; }