How to dynamically add elements to String array?

arraylist, arrays, java, string

Solution

`Arrays` in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a `List`:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

Problem

I want to add dynamic number of elements to a string array from inside a for loop. How to create an string array of an undefined length?

Original source