26

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");
Community
  • 1
  • 1
zeymav
  • 281
  • 1
  • 3
  • 5
  • You can look at this link : [Add elements to a string array][1] [1]: http://stackoverflow.com/questions/2843366/how-to-add-new-elements-to-a-string-array – Haimo Jan 25 '13 at 08:46

5 Answers5

33

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"); 
rsjaffe
  • 5,600
  • 7
  • 27
  • 39
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
21

You can't do it the way you wanted.

Use ArrayList instead:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");

And then you can have an array again by using toArray:

String[] myArray = new String[a.size()];
a.toArray(myArray);
Maroun
  • 94,125
  • 30
  • 188
  • 241
5

Simple answer: You can't. An array is fixed size in Java. You'll want to use a List<String>.

Alternatively, you could create an array of fixed size and put things in it:

String[] array = new String[2];
array[0] = "Hello";
array[1] = "World!";
WorkingRobot
  • 423
  • 8
  • 19
akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
5

You can't. A Java array has a fixed length. If you need a resizable array, use a java.util.ArrayList<String>.

BTW, your code is invalid: you don't initialize the array before using it.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0
String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

suresh manda
  • 659
  • 1
  • 8
  • 25