简体   繁体   中英

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. 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:

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. 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 . 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.

Try using this for-loop:

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. Therefore, it upped the boundary that i had to meet infinitely. 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.

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. The lower bound will always be 0 and the i will decrease towards 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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