ArrayList.remove is not working in a loop

后端 未结 7 1582
南旧
南旧 2020-11-29 09:46

I have following code-

import java.util.ArrayList;

public class ArrayListExp{
    public static void main (String[] args){

        ArrayList          


        
相关标签:
7条回答
  • 2020-11-29 10:21

    You're removing from the ArrayList while iterating over it from 0 to N, so when you remove the first Meg at index N, the next Meg moves down to index N, then you increment i to N+1. So the 2nd Meg doesn't get removed. Try iterating in the opposite order (N to 0):

    for ( int i = name.size() - 1;  i >= 0; i--) {
    
    0 讨论(0)
提交回复
热议问题