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?

2
  • You mean you want to increase size of array dynamically Commented Dec 10, 2017 at 6:19
  • if so than its language specific Commented Dec 10, 2017 at 6:19

4 Answers 4

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

This gonna create a new instance rather than increasing the size of existing array
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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.