Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง Iterator และ ListIterator ใน Java

Iterator

  • Iterate: Map, List, Set
  • ไม่ได้ index
  • ไม่สามารถ modify/replace element ได้ (แค่ remove)
  • ทิศทาง: Forward only
  • ไม่สามารถ add element ขณะ iterate (ConcurrentModificationException)
  • Methods: hasNext(), next(), remove()

ListIterator

  • Iterate: List เท่านั้น (ไม่ใช่ Map/Set)
  • ได้ index: nextIndex(), previousIndex()
  • ทิศทาง: Forward และ Backward (next(), previous())
  • Modify/Replace ได้: set()
  • Add ได้: add() ตลอดเวลา
  • Methods: hasNext(), next(), hasPrevious(), previous(), nextIndex(), previousIndex(), remove(), set(), add()

สรุป

คุณสมบัติIteratorListIterator
Collection TypesMap, List, SetList เท่านั้น
DirectionForwardForward + Backward
Index Accessไม่ได้ได้ (nextIndex, previousIndex)
Modify/Replaceไม่ได้ได้ (set)
Add Elementไม่ได้ได้ (add)