简体   繁体   English

ArrayList for 循环迭代器导致无限循环

[英]ArrayList for loop iterator causing infinite loop

I'm trying to iterate through an ArrayList and print each element in it but it only outputs the first element in the ArrayList.我试图遍历一个 ArrayList 并打印其中的每个元素,但它只输出 ArrayList 中的第一个元素。 Then there's an infinite loop and it keeps printing out the first element.然后是一个无限循环,它不断打印出第一个元素。

ArrayList<String> startTime = new ArrayList<String>();

for (int i = 0; i < startTime.size(); i++) {
    String getTime = startTime.get(i);
    getTime = convertTime(getTime);
    startTime.add(i, getTime);
    System.out.println(startTime.get(i));
}

Definitly use advanced for-loops:绝对使用高级 for 循环:

ArrayList<String> startTime = new ArrayList<String>();
for(String aStartTime: startTime){
  // do something
}

When you do startTime.add(i, getTime) you are adding an element in the i position.当您执行startTime.add(i, getTime)您将在i位置添加一个元素。 That means in your next iteration, you are going to have an extra element in your list.这意味着在您的下一次迭代中,您的列表中将有一个额外的元素。 When you increment the counter and check startTime.size() , it's always going to be true .当您增加计数器并检查startTime.size() ,它总是会是true Hence your infinite loop.因此你的无限循环。

As a suggestion, if you want to add your getTime element, you might want to use some sort of auxiliary structure, like another List.作为建议,如果您想添加getTime元素,您可能需要使用某种辅助结构,例如另一个 List。

Try using this for-loop:尝试使用这个 for 循环:

for(int i=0,n=startTime.size();i<n;i++){
    //your for-loop code here  

}

When you were adding elements to startTime , it was increasing its size.当您向startTime添加元素时,它会增加其大小。 Therefore, it upped the boundary that i had to meet infinitely.因此,它提高了i必须无限满足的边界。 In my example, n will be set to startTime 's size at the beginning of the loop and won't change as the loop executes.在我的示例中, n将在循环开始时设置为startTime的大小,并且不会随着循环执行而改变。

You can try doing the loop backward (from the last element to the first element ) such as:您可以尝试向后循环(从最后一个元素到第一个元素),例如:

// assume that I have ArrayList variable named *list*

for(int i = list.size() - 1 ; i >= 0 ; i--){
    list.add(//something);
}

this code won't give you an infinite loop since the loop control variable never going to change ( i >= 0 ) even though your list size keeps changing.这段代码不会给你一个无限循环,因为即使你的列表大小不断变化,循环控制变量也永远不会改变( i >= 0 )。 The lower bound will always be 0 and the i will decrease towards 0下限将始终为 0,而i将向 0 递减

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM