0

so this would be my class:

public class ListArray {
     private String[] array;
     private int numElements;

     public void reSize{

     }

What's the best way to reSize "array"?

I was thinking doing something like this

 String newArray = new String[array.size]
 for (int i = 0; i < array.length; i++){
      newArray[i] = array[i];
 }
 array = new String[array.size *10]; //resize to 10x original size

then copying everything over from newArray to the "new" array.

But that seems very inefficient. Are there better ways?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
cplusalex
  • 83
  • 4
  • 3
    Yes. Just drop the first, useless copy. Create a new, larger array, then copy all the elements to the larger array, then set `this.array` to the larger array. – JB Nizet May 05 '19 at 17:13
  • 3
    Or just use `array = Arrays.copyOf(array, newSize)`. – Andy Turner May 05 '19 at 17:13
  • See also https://stackoverflow.com/questions/13197702/resize-an-array-while-keeping-current-elements-in-java – Jay May 05 '19 at 17:14

0 Answers0