在java中,将数组列表添加到for循环内部的列表中
我正在尝试将数组列表添加到for循环内部的列表中。在我的代码中,场景 是数组列表,假设它在每个i中都有一个新值。对于每个i我都想将场景保存在一个场景列表中,但我有这个错误在java中,将数组列表添加到for循环内部的列表中,java,arrays,list,for-loop,arraylist,Java,Arrays,List,For Loop,Arraylist,我正在尝试将数组列表添加到for循环内部的列表中。在我的代码中,场景 是数组列表,假设它在每个i中都有一个新值。对于每个i我都想将场景保存在一个场景列表中,但我有这个错误 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 你知道我该怎么修吗 int[] ActionArrayTest = new int[25]; int[] test27Augest = new
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
你知道我该怎么修吗
int[] ActionArrayTest = new int[25];
int[] test27Augest = new int[75];
ArrayList<Hour> scenario = new ArrayList<Hour>();
List<ArrayList<Hour>> list_of_scenarios = new ArrayList<ArrayList<Hour>>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
int[]ActionArrayTest=newint[25];
int[]test27Augest=新的int[75];
ArrayList场景=新建ArrayList();
List of_scenarios=new ArrayList();
对于(int i=1;i,在循环的第一次迭代中,list of_scenarios.add(i,scenario);
要求将scenario
添加到ArrayList的索引1中。但是,此时,ArrayList
为空
建议的解决方案:
for (int i = 0; i < 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
list_of_scenarios.add(i, scenario);
}
for(int i=0;i<100;i++){
ActionArrayTest=functional();
test27Augest=填充优先级(ActionArrayTest);
场景=函数B(test27Augest);
列出所有场景。添加(i,场景);
}
注意:声明此方法在该索引处添加元素,但将所有其他内容向右移动
如果要构造ArrayList
,使索引0处的元素添加到索引1处的元素之前,请使用普通的add()
方法:
列出场景。添加(场景);
只需将元素添加到列表的“末尾”即可。您是否正在尝试创建一个arraylist of arraylist..这听起来不是一种好的编程方法。如果您想在列表中找到元素,这将花费大量时间。请考虑代码复杂性以查找最后一个arraylist中的最后一个元素。您必须遍历列表列表,获取每个列表,再次遍历每个列表以查找该元素
如果所有这些arraylist都具有相同的类型,为什么不能将所有这些元素添加到顶级数组列表中呢?因此,您只维护一个arraylist,并且在执行for循环时,将Scenario的元素添加到arraylist中
像这样
List<Hour> list_of_scenarios = new ArrayList<Hour>();
for (int i = 1; i <= 100; i++) {
ActionArrayTest = FunctionA ();
test27Augest = Fill_the_prefrences(ActionArrayTest);
scenario = FunctionB(test27Augest);
//add all the elements of 'scenario' to the list.
list_of_scenarios.addAll(scenario);
}
List of_scenarios=new ArrayList();
对于(int i=1;我至少读取了引发异常的方法的文档。您正在从位置1开始循环..而您的数组列表当时为空..从位置0开始只需使用list\u of\u场景。添加(场景)
或以0而不是1开始i
。你应该排除你的代码改进建议,并解释OP为什么会得到他们得到的错误,因为这将是这个问题的实际答案。我只能给出我所知道的。令人惊讶的是,看到人们在这里带来嫉妒或某种恼人的东西。这是应该是知识共享平台。我没有说我的答案是正确的。我只给出了我所知道的,是否使用它取决于用户。期待与聪明而优秀的开发人员合作。