Posted By

kelvin101 on 10/07/16


Tagged

arrays expand immutable


Versions (?)

ArrayExpansion


 / Published in: Java
 

This class is an add-on for the arrays. Because arrays are immutable, this helper class has a method that will expand an array by the given value. After expansion is complete, user just has to call the getArray method to get the new, expanded array.

  1. /*
  2.  * Copyright (c) 2016. Ethan Hann
  3.  */
  4.  
  5. /**
  6.  * This class is an add-on for the arrays. Because arrays are immutable, this helper class has a method that
  7.  * will expand an array by the given value. After expansion is complete, user just has to call the getArray
  8.  * method to get the new, expanded array.
  9.  */
  10. public class ArrayExpansion {
  11. private int[] arr;
  12.  
  13. public ArrayExpansion(int[] array)
  14. {
  15. this.arr = array;
  16. }
  17.  
  18. /**
  19.   * Expand the original array by the specified value
  20.   * @param x : the number of indices to add to the original array
  21.   */
  22. public void expand(int x)
  23. {
  24. int[] copy = arr;
  25. arr = new int[copy.length + x];
  26. for (int i = 0; i < copy.length; i++)
  27. {
  28. arr[i] = copy[i];
  29. }
  30. copy = null;
  31. }
  32.  
  33. /**
  34.   * Get the new, expanded array
  35.   * @return arr : the new array
  36.   */
  37. public int[] getArray()
  38. {
  39. return arr;
  40. }
  41. }

Report this snippet  

You need to login to post a comment.