gpt4 book ai didi

Java,如何调整二维数组的第二个维度?

转载 作者:行者123 更新时间:2023-12-01 17:30:11 24 4
gpt4 key购买 nike

在我的应用程序中,我需要一个二维数组。如果我定义它修复它工作正常,如下所示:

static final String arrGroupelements[] = {"India", "Australia", "England", "South Africa"};
static final String arrChildelements[][] = { {"Sachin Tendulkar", "Raina", "Dhoni", "Yuvi" },
{"Ponting", "Adam Gilchrist", "Michael Clarke"},
{"Andrew Strauss", "kevin Peterson", "Nasser Hussain"},
{"Graeme Smith", "AB de villiers", "Jacques Kallis"} };

但是,在我的代码中我有两个列表。第一个是我可以获得的食谱名称列表。

LinkedList<String> recipeList = dbShoppingHandler.getAllRecipeNames();
String arrGroupelements[] = new String[recipeList.size()];
for(int i=0; i<recipeList.size(); i++) {
arrGroupelements[i] = recipeList.get(i);
}

我的第二个 list 是成分 list 。为了获取成分列表,我需要设置食谱名称,然后我才能获取列表。但是,我不知道如何将此列表作为第二维。我的代码是这样的:

String arrChildelements[][] = new String[recipeList.size()][20];
for(int i=0; i<recipeList.size(); i++) {
LinkedList<String> ingredient = dbShoppingHandler.getIngredientsOfRecipeName(recipeList.get(i));
for(int j=0; j<ingredient.size(); j++) {
arrChildelements[i][j] = ingredient.get(j);
}
}

坏事是,我需要为第二个维度设置一个数字(在我的例子中为 20)。如果我喜欢这样,对于有 5 个项目的列表,我将有 15 个“”元素,而那些有超过 20 个项目的列表,代码会忽略它们。

第一个维度是固定的,但我需要根据成分数量调整第二个维度。

任何建议都值得赞赏。谢谢。

最佳答案

如何分配所需大小的数组:

String arrChildelements[][] = new String[recipeList.size()][];
// not mentioning second dimension size ^^
for(int i=0; i<recipeList.size(); i++) {
LinkedList<String> ingredient = dbShoppingHandler.getIngredientsOfRecipeName(recipeList.get(i));
arrChildelements[i] = String[ingredient.size()];
// assigning new array here ^^
for(int j=0; j<ingredient.size(); j++) {
arrChildelements[i][j] = ingredient.get(j);
}
}

关于Java,如何调整二维数组的第二个维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11824720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com