Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add elements to String array? [closed]

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?

like image 508
omerjerk Avatar asked Feb 23 '13 10:02

omerjerk


People also ask

How do you dynamically add elements to an array?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.

How do you add items to a string array in Java?

You can also add an element to String array by using ArrayList as an intermediate data structure. An example is shown below. As shown in the above program, the string array is first converted into an ArrayList using the asList method. Then the new element is added to the ArrayList using the add method.

How do you add to an entire array?

For adding an element to the array, First, you can convert array to ArrayList using 'asList ()' method of ArrayList. Add an element to the ArrayList using the 'add' method. Convert the ArrayList back to the array using the 'toArray()' method.


2 Answers

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. 
like image 76
Jave Avatar answered Sep 17 '22 08:09

Jave


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

like image 34
Riskhan Avatar answered Sep 19 '22 08:09

Riskhan