| Resize a generic array |
|
|
|
| Written by Charles | |||||
| Saturday, 21 November 2009 19:43 | |||||
|
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; } }
Only registered users can write comments!
Powered by !JoomlaComment 3.26
3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved." |
|||||
| Last Updated ( Saturday, 21 November 2009 20:28 ) |



