120 likes | 187 Views
CSC 205 – Java Programming II. Lecture 29 March 25, 2002. Drawbacks of LinkedList. Unsatisfactory performance when accessing elements by index add(4, new Character(‘u’));. first. last. A. c. c. o. n. t. 0. 1. 2. 3. 4. 5. u. Solution: ListIterator.
E N D
CSC 205 – Java Programming II Lecture 29 March 25, 2002
Drawbacks of LinkedList • Unsatisfactory performance when accessing elements by index • add(4, new Character(‘u’)); first last A c c o n t 0 1 2 3 4 5 u
Solution: ListIterator • Methods defined in ListIterator • public boolean hasNext() • public boolean hasPrevious() • public Object next() • public Object previous() • public void remove() • public void add(Object o) • public void set(Object o) • public int nextIndex() • public int previousIndex ()
Example LinkedList letters = new LinkedList(); ListIterator lItr = letters.listIterator(); lItr.add(new Character('f')); lItr.add(new Character('t')); lItr.previous(); lItr.previous(); lItr.add(new Character('e')); lItr.add(new Character('r')); lItr.next(); lItr.add(new Character('e')); lItr.add(new Character('c')); lItr = letters.listIterator(); lItr.add(new Character('p'));
A perfect Example first f t First two add and two previous first Two more add one next e r f t Two more Add, one list- Iterator first e r f e r t first p e r f e r t
Creating ListIterator • Creating ListIterator through listIterator methods only • listIterator() • listIterator(int index)
Using ListIterator • Relative positions: one convenient view • Interleaf ListIterator positions with element positions first last A c c o n t 0 1 2 3 4 5 listIterator() listIterator(a.size()) listIterator(0)
Using ListIterator • Adding elements itr.add(new Character(‘u’)); u first last A c c o n t 0 1 2 3 4 5 Current position of The listIterator
Using ListIterator • After adding ‘u’ into the list, we have • itr.next() ‘n’ • Itr.previous() ‘u’ • One problem: this loop never stops lItr = fruits. listIterator(fruits.size()); while (lItr.hasPrevious()) { System.out.println(lItr.previous()); lItr.add("Pears"); }
Using ListIterator • This loop works fine fruits.add("Kumquats"); fruits.add("Bananas"); fruits.add("Kiwi"); fruits.add("Apples"); lItr = fruits.listIterator(); while (lItr.hasNext()) { System.out.println(lItr.next()); lItr.add("Pears"); }
Using ListIterator • Relative positions: the normal view first last A c c o n t 0 1 2 3 4 5 listIterator() listIterator(0) listIterator(a.size())
Using ListIterator • The next method advances to the next position, but returns the element that had been in the current position • Similar to the post-increment operator (i++) • The previous method first retreats to the position before the current position, and then returns the element at that retreated-to position • Similar to the pre-decrement operator (--i)