Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Doubling the size of an array

import java.lang.reflect.Array; public class MainClass {   public static void main (String args[]) {     int[] array = (int[])Array.newInstance(int.class, 3);     for(int i=0;i<array.length;i++){       array[i] = i;            }              int[] arrayDoubled = (int[])doubleArray(array);     for (int i: arrayDoubled) {       System.out.println(i);     }   }   static Object doubleArray(Object original) {     Object returnValue = null;     Class type = original.getClass();     if (type.isArray()) {       int length = Array.getLength(original);       Class elementType = type.getComponentType();       returnValue = Array.newInstance(elementType, length*2);       System.arraycopy(original, 0, returnValue, 0, length);     }     return returnValue;   } } 0 1 2 0