首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

idsIterator.remove()抛出IllegalStateException

idsIterator.remove() 抛出 IllegalStateException 的原因通常是因为在调用 remove() 方法之前,没有先调用 next() 方法。Iteratorremove() 方法需要在调用 next() 方法之后才能使用,因为它需要知道要删除的元素。

以下是一个简单的示例,说明如何正确使用 Iteratorremove() 方法:

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);

        Iterator<Integer> idsIterator = ids.iterator();
        while (idsIterator.hasNext()) {
            int id = idsIterator.next();
            if (id == 2) {
                idsIterator.remove(); // 在调用 next() 之后调用 remove()
            }
        }

        System.out.println(ids); // 输出: [1, 3]
    }
}

在这个示例中,我们在调用 remove() 方法之前先调用了 next() 方法,所以不会抛出 IllegalStateException

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券