Collections

36 阅读1分钟

Iterator

Trying to add/remove items in a collection using a for loop or a for-each loop would not work correctly, because the collection is changing size at the same time that the code is trying to loop.

So, simply loop through —→ for loop, for-each

add/remove —→ Iterator (backwards遍历其实也行

Iterator对象的三个方法:

  1. hasNext() 返回boolean值,判断是否有下一个元素
  2. next() 获取当前元素并移动到下一个元素
  3. remove()删除当前next()返回的元素(只能在next()之后调用一次)

注意:在LinkedList中,Iterator比get(i)高效

如果想在List中双向遍历或者修改元素,可使用ListIterator。除了上述三个方法外,ListIterator还额外有以下方法:

  1. hasPrevious()
  2. previous()
  3. add(E e) 在当前位置插入元素
  4. set(E e) 修改当前元素