Possible Duplicate:
how to add new elements to a String[] array?
How can I add new item to the String array ? I am trying to add item to the initially empty String. Example :
String a []; a.add("kk" ); a.add("pp");
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.
If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.
From arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.
So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.
String[] arr = new String[10]; // 10 is the length of the array. arr[0] = "kk"; arr[1] = "pp"; ...
So if your requirement is to add many objects, it's recommended that you use Lists like:
List<String> a = new ArrayList<String>(); a.add("kk"); a.add("pp");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With