Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. public class ExpandingArray
  2. {
  3. private static final int STARTING_SIZE = 10;
  4. private int[] arr;
  5. private int currentSize;
  6. private int numElements;
  7.  
  8. public ExpandingArray()
  9. {
  10. arr = new int[STARTING_SIZE];
  11. currentSize = STARTING_SIZE;
  12. numElements = 0;
  13. }
  14.  
  15. // Remove the element at index `index` and shift
  16. // all subsequent elements to the left.
  17. public int remove(int index)
  18. {
  19. int removed = arr[index];
  20. int[] olda = new int [currentSize -1];
  21. for (int i=0; i<index; i++)
  22. {
  23. olda[i] = arr[i];
  24. }
  25. for (int i=index; i<olda.length; i++)
  26. {
  27. olda[i] = arr[i+1];
  28. }
  29. arr = olda;
  30. return removed;
  31. }
  32.  
  33. // Add the int `element` at the `index` in the array.
  34. // You'll need to shift everything one index to the right
  35. // after this index.
  36. public void add(int index, int element)
  37. {
  38. int newa[] = new int[currentSize+1];
  39. for(int i =0; i<index; i++)
  40. {
  41. newa[i] = arr[i];
  42. }
  43. newa[index] = element;
  44. for(int i = index + 1; i<= newa.length - 1; i++)
  45. {
  46. newa[i] = arr[i - 1];
  47. }
  48. arr= newa;
  49. }
  50.  
  51. // Return the number of elements in your array.
  52. public int size()
  53. {
  54. return arr.length;
  55. }
  56.  
  57. private boolean isFull()
  58. {
  59. return numElements == currentSize;
  60. }
  61.  
  62. private void expand()
  63. {
  64. System.out.println("Expanding");
  65. int newSize = currentSize * 2;
  66. int[] newArray = new int[newSize];
  67.  
  68. // Copy over old elements
  69. for(int i = 0; i < currentSize; i++)
  70. {
  71. newArray[i] = arr[i];
  72. }
  73.  
  74. currentSize = newSize;
  75. arr = newArray;
  76. }
  77.  
  78. public int get(int index)
  79. {
  80. return arr[index];
  81. }
  82.  
  83. public void add(int x)
  84. {
  85. if(isFull())
  86. {
  87. expand();
  88. }
  89. arr[numElements] = x;
  90. numElements++;
  91. }
  92.  
  93. public String toString()
  94. {
  95. String str = "{";
  96. for (int i=0; i < numElements-1; i++) {
  97. str += arr[i] + ", ";
  98. }
  99. if (str.length() > 0 && str.charAt(str.length()-2)==',') {
  100. str = str.substring(0, str.length()-2);
  101. str += "}";
  102. }
  103. return str;
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement