Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add new item to the String array? [duplicate]

Tags:

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"); 
like image 876
zeymav Avatar asked Jan 25 '13 08:01

zeymav


People also ask

Can you add to string arrays?

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 a new element to an array?

If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

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

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.


1 Answers

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.

enter image description here

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");  
like image 131
Sumit Singh Avatar answered Oct 16 '22 16:10

Sumit Singh