+ 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?

13th Sep 2019, 6:52 PM
Jamie Charles
6 Antworten
+ 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!
13th Sep 2019, 6:57 PM
Anton Böhler
Anton Böhler - avatar
+ 3
or use a fancy LinkedList 😜
13th Sep 2019, 7:22 PM
Anton Böhler
Anton Böhler - avatar
+ 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.
13th Sep 2019, 7:06 PM
Seb TheS
Seb TheS - avatar
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
14th Sep 2019, 12:07 AM
Denise Roßberg
Denise Roßberg - avatar