-1

I have a method that's supposed to grow the size of an array by double once it reaches its capacity

I was trying to find a way to resize it without Arrays.copyOf but rather creating an array that's double the size and storing the original array in the new resized array

works

this.capacity = this.capacity * 2;
this.theData = Arrays.copyOf(this.theData, this.capacity);

doesn't work rather it throws away the first index and replaces it with the new value, without resizing

double arrayResize[] = new double[this.capacity*2];
for (int i = 0; i<this.theData.length;i++){
        arrayResize[i] = this.theData[i];
}
Paige
  • 159
  • 6
  • 2
    [Resize an Array while keeping current elements in Java?](https://stackoverflow.com/q/13197702/995714), [How can I resize array in java?](https://stackoverflow.com/q/43499183/995714) – phuclv Sep 28 '21 at 04:41
  • 6
    Your second solution should work, as long as you do assign arrayResize to theData. – tgdavies Sep 28 '21 at 04:44
  • @tgdavies and assign `capacity = 2*capacity` as well. – Andy Turner Sep 28 '21 at 05:25
  • 1
    Btw, I don't think having the `capacity` field is necessary: it looks like it is equal to the array length, so you may as well just use the array length. – Andy Turner Sep 28 '21 at 05:26
  • Does this answer your question? [Resize an Array while keeping current elements in Java?](https://stackoverflow.com/questions/13197702/resize-an-array-while-keeping-current-elements-in-java) – mmmmmm Sep 28 '21 at 17:14

1 Answers1

1

You cannot resize an array in Java. Use ArrayList or LinkedList instead.

If you need to have a list for a primitive types and you don't want to wrap them into objects, take a look on Colt or Parallel Colt libraries.

30thh
  • 10,861
  • 6
  • 32
  • 42