Download presentation
Presentation is loading. Please wait.
1
CSC 205 – Java Programming II
Lecture 29 March 25, 2002
2
Drawbacks of LinkedList
Unsatisfactory performance when accessing elements by index add(4, new Character(‘u’)); first last A c c o n t 1 2 3 4 5 u
3
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 ()
4
Example LinkedList letters = new LinkedList();
ListIterator lItr = letters.listIterator(); lItr.add(new Character('f')); lItr.add(new Character('t')); lItr.previous(); lItr.add(new Character('e')); lItr.add(new Character('r')); lItr.next(); lItr.add(new Character('c')); lItr = letters.listIterator(); lItr.add(new Character('p'));
5
A perfect Example f t e r f t e r f e r t p e r f e r t first
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
6
Creating ListIterator
Creating ListIterator through listIterator methods only listIterator() listIterator(int index)
7
Using ListIterator Relative positions: one convenient view
Interleaf ListIterator positions with element positions first last A c c o n t 1 2 3 4 5 listIterator() listIterator(a.size()) listIterator(0)
8
Using ListIterator Adding elements itr.add(new Character(‘u’)); u A c
first last A c c o n t 1 2 3 4 5 Current position of The listIterator
9
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"); }
10
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"); }
11
Using ListIterator Relative positions: the normal view A c c o n t
first last A c c o n t 1 2 3 4 5 listIterator() listIterator(0) listIterator(a.size())
12
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.