Sometimes you will have an array that is declared with generics, such as T[] a. You can't, unfortunately, do a = new T[somethingBigger]. You must use reflection. Below is how to do so. Of course, making it smaller would use exactly the same principle. The code is HERE
import java.lang.reflect.Array;
public class EnlargeArray<T> {
/**
* Just for demo
*
* @param args The command line args
*/
public static void main(String[] args) {
Integer[] myArray = { 1, 2, 3, 4 };
// Show original
System.out.println(java.util.Arrays.toString(myArray));
// Enlarge it twofold
myArray = EnlargeArray.doubleSize(myArray);
for(int i = 0;i < myArray.length;i++) {
myArray[i] = i + 1;
}
System.out.println(java.util.Arrays.toString(myArray));
}
/**
* Double the size of a generic array
*
* @param <T> The array element type
* @param original The original array
*
* @return The new array, doubled in size
*/
public static <T> T[] doubleSize(T[] original) {
T[] result = (T[]) Array.newInstance(original[0].getClass(), original.length * 2);
System.arraycopy(original, 0, result, 0, original.length);
return result;
}
}
public class EnlargeArray<T> {
/**
* Just for demo
*
* @param args The command line args
*/
public static void main(String[] args) {
Integer[] myArray = { 1, 2, 3, 4 };
// Show original
System.out.println(java.util.Arrays.toString(myArray));
// Enlarge it twofold
myArray = EnlargeArray.doubleSize(myArray);
for(int i = 0;i < myArray.length;i++) {
myArray[i] = i + 1;
}
System.out.println(java.util.Arrays.toString(myArray));
}
/**
* Double the size of a generic array
*
* @param <T> The array element type
* @param original The original array
*
* @return The new array, doubled in size
*/
public static <T> T[] doubleSize(T[] original) {
T[] result = (T[]) Array.newInstance(original[0].getClass(), original.length * 2);
System.arraycopy(original, 0, result, 0, original.length);
return result;
}
}