gpt4 book ai didi

java - 二维数组但带有索引 - java

转载 作者:行者123 更新时间:2023-11-29 05:35:39 25 4
gpt4 key购买 nike

我循环进入许多行并尝试使用一些 if 语句过滤这些行。在每个 if 语句中,我需要为多个元素创建一个索引。我本可以使用 2d String[][] 来做到这一点,但问题是我不知道现阶段每行的大小是多少。

我希望像下面这样存储我的数据:

    0     1    3    4    5    6    7  etc.. 
0 str str str str str str str
1 str str str
2
3 str str str str str str

如有任何建议,我们将不胜感激

 Edit:

抱歉,如果我的问题不清楚。但我会在这里详细解释。

我的循环看起来像这样:

newArrayList
for (i; i < List ;i++)
{
if(...)
{
newArrayList.add.(0, List.get(i));
} else if(...)
{
newArrayList.add.(2, List.get(i));
} else if(...)
{
newArrayList.add.(6, List.get(i));
}
}

上面的代码不起作用,但我只是想解释我实际上需要做什么!我的 if 语句可能会出现多次,我想为每个 if 语句期望加上一组字符串考虑一个索引。谢谢。

最佳答案

你可以试试 ArrayListArrayList的:

    ArrayList<ArrayList<String>> strings = new ArrayList<ArrayList<String>>();
strings.add(new ArrayList<String>()); // Adding a first array to the 'array of arrays'
strings.get(0).add("String1"); // Add a string to the first array,
// Similar to: arr[0][0] = "String1"

//To access them element by element use a double for, note that "s" is each element
for (ArrayList<String> l : strings) {
for (String s : l) {

}
}

附言:一个ArrayList<Object>就像一个数组 Object[]但更灵活。它有一些有用的方法,例如:

arr_list.get(index); // Getting an object in position 'index'
arr_list.add(object); // Adding an element (Similar to assignment in arrays)

编辑

如果您知道“行”的数量,那么您必须将它们添加到 array of arrays .有了这个for您正在“创建数组的空行”:

Rows:
0
1
...
n


for (int i = 0; i < n; i++) { // n is the number of "rows"
strings.add(new ArrayList<String>());
}

然后向“行”添加一个元素:

strings.get(0).add("String1"); // get(0) to obtain the first row, get(1) to obtain the second...

关于java - 二维数组但带有索引 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603840/

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