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

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");

This question is related to java arrays

The answer is


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.


String a []=new String[1];

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

Try this one...


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!";

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);