I have a problem related to storing data dynamically in two Dimensional String Array, String[][].
I am dynamically storing data in the String[i][j] array. Here the first index’s value is fixed i.e. i=3, but second index’s value is different for all rows.
for example, I am getting values like this,
String arrElements[][] = {
{"1"},
{"abc", "xyz", "lkm", "pwd", "srt", "qwert"},
{"1234", "3456"}
};
I am getting values something like this. i.e there is only 1 value in the first row, any number of values in the second row and in the third row.
If I go like this,
int i = 0, j = 0;
String arrElements[][] = {};
arrElements= new String[3][25];
//What size should I define here.
arrElements[0][0] = "Sahil";
if (a == 0) { //Its just a logical representation of what I might be doing.
// Store the value in second row
arrElements[1][i] = a;
i++;
}
if (a == 1) {
// Store the value in third row
arrElements[2][j] = a;
j++;
}
Now, I am setting these values in the expandable list View. If the number of values in any of the rows exceeds the size specified, it gives ArrayOutOfBoundException. and if the size is less than 25, it shows empty rows.
Now, I dont want to give hard coded size limit for the array indexes. Is there any better way to deal with it.
As a first remark: Are you sure a
String[][]is the right data structure for what you want to achieve? There is a whole bunch ofCollectionclasses that might be more suitable (ArrayListto name the most obvious).If you really want to proceed with
String[][]you can’t define the length of the sub-arrays upfront but have to declare it per row:But as I said you might be much happier with a nested
ArrayListwhich resizes dynamically:Depending on what you actually want to store, other data structures might be much more suited.