How to dynamically add elements to String array? [closed]
Solution 1:
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.
Solution 2:
when using String array, you have to give size of array while initializing
eg
String[] str = new String[10];
you can use index 0-9 to store values
str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"
if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();
you can add value by using add method of Arraylist
str.add("Value1");
get retrieve a value from arraylist, you can use get method
String s = str.get(0);
find total number of items by size method
int nCount = str.size();
read more from here
Solution 3:
You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask