0

我有一个与动态存储数据相关的问题two Dimensional String ArrayString[][]. 我在String[i][j]数组中动态存储数据。这里第一个索引的值是固定的,即i=3,但第二个索引的值对于所有行都是不同的。

例如,我得到这样的值,

String arrElements[][] = {
        {"1"},
        {"abc", "xyz", "lkm", "pwd", "srt", "qwert"},
        {"1234", "3456"}
        };

我得到这样的价值观。即第一行只有一个值,第二行和第三行有任意数量的值。

如果我这样走,

    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++;
    }

现在,我将这些值设置在expandable list View. 如果任何行中的值的数量超过指定的大小,则给出ArrayOutOfBoundException. 如果大小小于 25,则显示空行。

现在,我不想为数组索引提供硬编码大小限制。有没有更好的方法来处理它。

4

2 回答 2

1

你可以使用任何你喜欢的数据结构。

ExpandableListAdapter传递给视图的 中,只需确保从getGroupCount和中返回正确的值getChildrenCount。在getGroupandgetChild中,从您使用的任何支持结构(数据库游标、列表、列表列表等)返回适当的数据。

这种类型列表的一个有用结构是Map<GroupData, List<ChildData>>. 这可能就像HashMap<String, ArrayList<String>>项目文本是您拥有的唯一数据一样简单。

于 2013-01-17T08:24:53.980 回答
1

作为第一句话:您确定 aString[][]是您想要实现的正确数据结构吗?有一大堆Collection类可能更合适(ArrayList举个最明显的例子)。

如果你真的想继续,String[][]你不能预先定义子数组的长度,但必须每行声明它:

String[][] foo = new String[4][];
foo[0] = new String[1];
foo[1] = new String[2];
// .... 

ArrayList但正如我所说,您可能会对动态调整大小的嵌套更满意:

ArrayList<ArrayList<String>> foo = new ArrayList<ArrayList<String>>();
// Do the following for each row
foo.add(new ArrayList<String>>());
// Do the following to append data in row i
foo.get(i).add("new string");
// Do the following to retrieve column j in row i
foo.get(i).get(j);

根据您实际想要存储的内容,其他数据结构可能更适合。

于 2013-01-17T08:29:08.027 回答