Duplicate
How do I initialize string[] without a need of initializing the length? I want it to be dynamic array, so when I add something, Length increases and no Exception raises?
Should I just use some kind of List?
How do I initialize string[] without a need of initializing the length? I want it to be dynamic array, so when I add something, Length increases and no Exception raises?
Should I just use some kind of List?
I think a lot of languages out there will allocate the entire array as a block up front. You may need to use a wrapper class that provides this functionality. In the absence of a language specified, Java and C++ for example, int[] will be a contiguous block of memory. You'll have to allocate a new block and copy the old contents, or use a wrapper that manages this for you, either doing the same thing or using pointers to objects. That would be ArrayList or similar in Java.
If your using C# use ArrayList. It dynamically expands as you need it and it also can hold anything (this can be both good and bad). So yes you should use some kind of list. Also remember to include this using statement:
using System.Collections;
Arrays have a fixed length in most languages. You have to use a dynamic datatype like a list if you need dynamic length.
If the language does not suport lists natively, they are usually implemented with arrays. If the content becomes to long to fit into the array, a longer array is allocated, the content copied from the old array to the new one, and finally the old array is freed.
I am quite sure there is a dynamic length type in your language or one of its libraries.
UPDATE
For C# the collection classes are found in the System.Collections
namespace. You should focus on the generic classes in System.Collections.Generic
if possible. Four your case the generic List<String>
would probably fit best. But also Stack<String>
or Queue<String>
might be interesting.
What language?
C#, Java, and many other high-level languages have ArrayList
data structure (or something similar) that allow you to add and remove elements without setting a specific size.
If you need to have an array of unkown length of strings
, use a List<T>
from the System.Collections.Generic
namespace.
List<string> myList = new List<string>();
myList.Add("First");
myList.Add("Second");
myList.Add("Third");
myList.Count // = 3
This uses an array behind the scenes that is of a fixed size, but it hides the fact that it will make the array bigger and move all elements when it runs out of space.