Unit04B - 1 1 OOP A Deeper Look Iterators, The Collection...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 1 OOP A Deeper Look Iterators, The Collection Hierarchy 4B 2 Iterating over a list SinglyLinkedList< type > list = new SinglyLinkedList< type >(); ... for (int i=0; i<list.size(); i++) { type nextElement = list.get(i); // do something with nextElement } If the list has n elements, what is the order of complexity of this iteration? ________ 3 Iterators An iterator implements a "marker" in the list to keep track of the last element accessed so we can examine the next element quickly. null head marker hasNext - is the marker still pointing to data? next - return data value and move on to next element 4 Iterators Iterator< type > iter = list.iterator(); while (iter.hasNext()) { type nextElement = iter.next(); // do something with nextElement } If the list has n elements, what is the order of complexity of this iteration? ________ 5 The Iterator interface boolean hasNext() Returns true if there is another element to process. E next() Returns the next element. If there are no more elements, throws the NoSuchElementException . void remove() Removes the last element returned by the next method. (must be preceded by a call to next ) 6 Using Iterator interface If we say SinglyLinkedList implements Iterator , we can only have one iterator for the list. That is, the singly linked list acts as the iterator itself. Instead, we can create an iterator as an inner class. We can have more than one iterator for a list. 2 7 Creating iterators To use an iterator on a collection of data, we must supply an iterator method that returns an Iterator on this object. Example: in SinglyLinkedList class public Iterator<E> iterator() { return new SLLIterator(); } implementation later 8 Using iterators Example: Use an iterator to remove all integers in a singly-linked list of integers that are even. SinglyLinkedList<Integer> list = new SinglyLinkedList<Integer>(); ... Iterator<Integer> iter = list.iterator(); while (iter.hasNext()) { int num = iter.next(); if (num % 2 == 0) iter.remove(); } 9 The ! ListIterator<E> interface ListIterator is an extension of Iterator The LinkedList class implements the List<E> interface using a doubly-linked list....
View Full Document

This note was uploaded on 12/19/2009 for the course CS 121 taught by Professor Reid-miller during the Spring '09 term at Carnegie Mellon.

Page1 / 5

Unit04B - 1 1 OOP A Deeper Look Iterators, The Collection...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online