且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们需要在Java中使用迭代器上的ArrayList?

更新时间:2022-11-23 10:51:54

正如你们所指出的迭代器是用来当你想,而你遍历数组内容去掉的东西。如果不使用迭代器,而只是有一个for循环和里面使用remove方法,因为数组的内容发生变化,而你遍历你会得到异常。例如:你可能会认为数组大小是10日在for循环的开始,但它不会是,一旦你删除的东西..所以当u到达最后的循环可能会出现的情况下抛出IndexOutOfBoundsException等

As you have stated iterator is used when you want to remove stuff whilst you iterate over the array contents. If you don't use an iterator but simply have a for loop and inside it use the remove method you will get exceptions because the contents of the array changes while you iterate through. e.g: you might think array size is 10 at the start of the for loop but it wont be the case once you remove stuff.. so when u reach the last loops probably there will be IndexOutofBoundsException etc.