+ 1
How to double size of an array without making another array?
Say in the constructor of a class called SomeArray takes in a parameter int size and there is a private array of strings called strArray. I initialize the strArray with the size passed in. I then add elements into it. But then thereâs a method which has the purpose of doubling the size of the array and I cannot make new arrays directly. I know I can make a new SomeArray object and initialize it with the size doubled. But wonât the elements disappear? How do I keep the elements?
6 Answers
+ 4
you can't change the size of an existing array, but you can use an ArrayList which can change in size dynamically.
if you don't want to use an ArrayList then you should post your code here so we can give you better advise đ
happy coding!
+ 3
or use a fancy LinkedList đ
+ 2
But don't ArrayLists:
1. create a new array,
2. copy old array elements in the new array,
3. destroy old array.
when their sizes changes?
It just does it automatically.
0
Your class SomeArray needs two methods:
* to fill the array
* to get the String
In your method which doubles the size you create a new object of SomeArray and with these two methods above you are able to copy the values.
https://code.sololearn.com/cH5uvGGDle4j/?ref=app