0

Doubling the size of an array using a generic object?

In my code, the class SomeArray is generic and initializes an array called arr. It is initialized with a integer which determines the size of the array. I have a method which has to double the size of the array. I have to double it by creating and initializing a SomeArray object with the parameter being the current size doubled. I’m kind of confused on how this works though. What if there is elements inside the array, do they disappear? Because I think creating a new SomeArray object creates an empty copy of the arr array , so I don’t know how to save the elements first before they disappear, and I’m not allowed to create a new array directly.

12th Sep 2019, 5:06 PM
Jamie Charles
2 Réponses
0
Array is contiguous memory allocation.You can't double the size of Array. You have to initialise a new Array with double size and then copy all the elements of previous Array into new Array. It can be done by using two nested for loops, one loop for each array. If you don't want to create new Array then you have to use linked list or ArrayList data structures.
12th Sep 2019, 5:31 PM
Vijay Meena
0
Here is an easy code of doubling the size of an integer array: https://code.sololearn.com/c4p6xwnnCD60/?ref=app You just need a for loop which copies the values of the old array into the new one.
13th Sep 2019, 12:13 AM
Denise Roßberg
Denise Roßberg - avatar