Resizing Generic Arrays in Java in A Generic Way


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. package ch.hsr.ifs.liquid.util;
  2.  
  3. import static java.lang.System.arraycopy;
  4.  
  5. import java.lang.reflect.Array;
  6.  
  7. public class Arrays {
  8. private static final int ENLARGE_FACTOR = 2;
  9.  
  10. public static <T> T[] enlargeArray(T[] array) {
  11. T[] enlargedArray = initArray(array, array.length * ENLARGE_FACTOR);
  12. arraycopy(array, 0, enlargedArray, 0, array.length);
  13. return enlargedArray;
  14. }
  15.  
  16. public static <T> T[] trimArray(T[] array, int length) {
  17. T[] trimmedArray = initArray(array, length);
  18. arraycopy(array, 0, trimmedArray, 0, length);
  19. return trimmedArray;
  20. }
  21.  
  22. public static <T> T[] composeArray(T[] array1, T[] array2) {
  23. int length1 = array1.length;
  24. int length2 = array2.length;
  25.  
  26. T[] composedArray = initArray(array1, length1 + length2);
  27.  
  28. arraycopy(array1, 0, composedArray, 0, length1);
  29. arraycopy(array2, 0, composedArray, length1, length2);
  30.  
  31. return composedArray;
  32. }
  33.  
  34. @SuppressWarnings("unchecked")
  35. private static <T> T[] initArray(T[] array, int newSize) {
  36. return (T[]) Array.newInstance(array.getClass().getComponentType(), newSize);
  37. }
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.