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