2 回答
TA贡献1831条经验 获得超10个赞
Iterator在这种情况下,我实际上会放弃。而是尝试这样的代码:
List<Integer> list = ...;
for (int index = 0; index < list.size(); index++) {
final Integer val = list.get(index);
// did you want to add something once you reach an index
// or was it once you find a particular value?
if (index == 3) {
// to insert after the current index
list.add(index + 1, 6);
// to insert at the end of the list
// list.add(6);
}
System.out.println(val);
}
由于 for 循环i与size()每次迭代进行比较,并且size()在将元素添加到列表时进行更新,因此这会正确打印添加到列表中的新内容(只要它们添加在当前索引之后)。
TA贡献2019条经验 获得超9个赞
xtratic 的答案的主题在展示满足 OP 的要求需要做什么方面非常出色(竖起大拇指),但代码不能很好地完成工作,因此发布此代码正是 OP 想要的,
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
for (int index = 0; index < list.size(); index++) {
final Integer val = list.get(index);
if (index == 3) { // index doesn't have to be compared with 3 and instead it can be compared with 0, 1 or 2 or 4
list.add(5, 6); // we need to hardcodingly add 6 at 5th index in list else it will get added after 4 and will not be in sequence
}
System.out.println(val);
}
这输出以下序列,
1
2
3
4
5
6
在 for 循环中,如果我们这样做,
list.add(index+1, 6);
然后它会产生错误的序列,因为在第 4 个索引处添加了 6。
1
2
3
4
6
5
添加回答
举报