I have a listview.
private String[] listView2 = {"aa","aa","aa"};
int a = 0;
Int values will decide to add the number of content
So if a==2.
listView2 = {"aa","aa"};
if a==5
listView2 = {"aa","aa","aa","aa","aa"};
You're clearly familiar with array initializers where you specify the content up-front... but you can also create arrays just by specifying the length, like this:
String[] array = new String[length];
This will create an array where every element is a null reference (or the a 0, false or '\0'
for numeric, Boolean or character arrays respectively). You then just need to populate it. You could do that with a loop:
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = "aa";
}
Or you could use the Arrays.fill
method:
String[] array = new String[length];
Arrays.fill(array, "aa");
One comment on your title though - it's worth understanding that once you've created an array, you can't actually add elements to it (or remove elements from it). The array object has a fixed size. If you do:
String[] array = new String[4];
...
array = new String[5];
then that doesn't add an element to the array - it creates a new array of length 5, and assigns a to that array to the variable array
. Any other variables which still have a reference to the original array won't see any change.
See more on this question at Stackoverflow