0

I have an assignment for class that requires increasing the size of an arrays index. The instruction mentions not to create a new array and copying the elements, calling it rather inefficient. Instead they suggest the following

"A more common strategy is to choose an initial size for the array and add elements until it is full, then double its size and continue adding elements until it is full, and so on."

I'm having trouble wrapping my head around this. How would I got about accomplishing this?

hyeonk
  • 1
  • 1
  • 2

4 Answers4

0

You can double the size of an array if you multiply the lenght of your current array, like this:

array = Arrays.copyOf(array, array.lenght*2); 
0

Initial size for the array and add elements until it is full, then double its size and continue adding elements until it is full, and so on.

This is statement clearly shows to use java ArrayList as this strategy is used in ArrayList. This is how it is declared.

List<Your_DataType> lst=new ArrayList<>();

e.g.

List<Integer> lst=new ArrayList<>();

lst.add(1);
lst.add(2);
lst.add(3);
lst.get(0);// shows 1 which is at 0th location
lst.get(1);// shows 2 which is at 0th location
lst.get(2);// shows 3 which is at 0th location
Suvam Roy
  • 963
  • 1
  • 8
  • 19
0

You have to create a new array or you can do something like :

int a[] = new a[10];
a = Arrays.copyOf(a, a.length + arrayGrowNumber);

In above example you are just copying your existing array to a new array defined with large size array.

For more information please visit this link.

Lalit Verma
  • 782
  • 10
  • 25
0

Your instructions are conflicting. The "common strategy" instructions will still "create a new array and copying the elements", but will do so less often.

Say you create the array at size 20, then begin adding a total of 50 values.

After adding first 20, you create a new array of size 40 and copy values over, then continue adding to the new array.

After adding 20 more (total of 40), you create a new array of size 80 and copy values over, then continue adding to this new array.

When you've added all 50 values, you have an array of size 80, with values in the first 50 positions. You've copied the array twice.

Saying that you cannot create a new array is misleading/wrong. You have to. The "common strategy" instruction of "double its size" requires it.

Andreas
  • 154,647
  • 11
  • 152
  • 247