[英]Modifying and printing ArrayList during iteration
我正在嘗試同時修改和打印修改后的列表。 以下是示例代碼:
public class Test {
static List<Integer> l = new ArrayList<Integer>()
{{
add(1);
add(2);
add(3);
add(4);
add(5);
}};
public static void main(String args[])
{
performTask();
}
private static void performTask()
{
int j = 0;
ListIterator<Integer> iter = l.listIterator();
while(iter.hasNext())
{
if(j == 3)
{
iter.add(6);
}
System.out.println(l.get(j));
iter.next();
++j;
}
}
}
我期望輸出為1,2,3,6,4,5
但輸出是1,2,3,6,4
。 另外,如果我想獲得輸出為1,2,3,4,5,6
,應該如何修改代碼?
在這種情況下,我實際上會放棄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()
,因此可以正確打印添加到列表中的新內容(只要它們在當前索引)。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.