Computer Science 112 Fundamentals of Programming II List Iterators.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Linked Lists Linear collections.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
1 Joe Meehean. Ordered collection of items Not necessarily sorted 0-index (first item is item 0) Abstraction 2 Item 0 Item 1 Item 2 … Item N.
The List ADT Textbook Sections
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Iterators and Sequences1 © 2010 Goodrich, Tamassia.
Computer Science 112 Fundamentals of Programming II Array-Based Queues.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Computer Science 209 Software Development Iterators.
Computer Science 112 Fundamentals of Programming II Lists.
Fundamentals of Programming II Inheritance and Abstract Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
(c) University of Washington14-1 CSC 143 Java Collections.
The Java Collections Framework Chapters 7.5. Outline Introduction to the Java Collections Framework Iterators Interfaces, Abstract Classes and Classes.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
LinkedList Many slides from Horstmann modified by Dr V.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
Built-in Data Structures in Python An Introduction.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Computer Science 112 Fundamentals of Programming II Implementation Strategies for Unordered Collections.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
COM S 228 Collections and Iterators Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff 201.
Computer Science 209 Software Development Inheritance and Composition.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Computer Science 112 Fundamentals of Programming II Iterators.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Fundamentals of Programming II Linked Lists
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Iterators
Fundamentals of Programming II Working with Arrays
Fundamentals of Programming II Binary Search Trees
Software Development Inheritance and Composition
Fundamentals of Programming II Interfaces and Implementations
Computer Science 112 Fundamentals of Programming II
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Dynamic Data Structures and Generics
Computer Science and Engineering
Collections Framework
Iterators Dan Fleck.
Presentation transcript:

Computer Science 112 Fundamentals of Programming II List Iterators

lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) rator = aList.listIterator() rator.last() while rator.hasPrevious(): # print in reverse order print(rator.previous()) Opening a List Iterator on a List Maintains a cursor to access the list ratorlyst

LI = L.listIterator() returns a new list iterator object on a list LI.first() moves the cursor to the first item LI.hasNext() returns true if there are any items following the current position LI.next() returns the next item and advances the position LI.last() moves the cursor to the last item LI.hasPrevious() returns true if there are any items preceding the current position LI.previous() returns the previous item and moves the position backward Position-Based Operations for Navigation Similar to an extended iterator

LI.insert(newItem) inserts newItem at the current position LI.remove() removes the last item returned by next or previous LI.replace(newItem) replaces the last item returned by next or previous Position-Based Operations for Mutation

Mutations with a List Iterator lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Replace all ints with 0s for i in range(len(lyst)): lyst[i] = 0 Using an index-based loop with the subscript would be O(n 2 ) with a linked list

Mutations with a List Iterator lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Replace all ints with 0s rator = lyst.listIterator() while rator.hasNext(): rator.next() rator.replace(0) Using an index-based loop with the subscript would be O(n 2 ) with a linked list

Can Do Just One Insertion lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Insert 1s before each integer rator = lyst.listIterator() while rator.hasNext(): rator.next() rator.insert(1)

Can Do Just One Insertion lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Error: must have a separate next() prior to each add rator = lyst.listIterator() while rator.hasNext(): rator.next() rator.insert(1) rator.insert(2)

Using a Mutator to Clear the List lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Clear the list (make it empty) rator = lyst.listIterator() while rator.hasNext(): rator.next() rator.remove()

Cant Use List Mutators lyst = LinkedList(range(11, 21)) # or ArrayList(range(11, 21)) # Clear the list (make it empty) rator = lyst.listIterator() while rator.hasNext(): lyst.pop() rator.next() rator.remove() Directly mutating the backing store in the context of an iterator can cause the store and the iterator to become inconsistent The iterator will need to know when the store has changed and raise an exception in that event

Tracking Mutations The list and its iterator each keep separate modCount variables The lists modCount is initially 0, and is incremented on each mutation The iterators modCount is initialized to the lists current modCount Each call of next or previous compares the counts, and if theyre different, raises an exception

The Lists modCount class AbstractList(AbstractCollection): """Represents an abstract list.""" def __init__(self, sourceCollection): """Maintains a count of modifications to the list.""" self._modCount = 0 AbstractCollection.__init__(self, sourceCollection) def getModCount(self): return self._modCount def incModCount(self): self._modCount += 1

The Lists modCount class ArrayList(AbstractList): """Represents an array-based list.""" DEFAULT_CAPACITY = 8 def __init__(self, sourceCollection = None): self._items = Array(ArrayList.DEFAULT_CAPACITY) AbstractList.__init__(self, sourceCollection) def pop(self, i = len(self - 1)): """Precondition: 0 <= i < len(self) Removes and returns the item at position i.""" if i = len(self): raise IndexError("List index out of range") item = self._items[i] for j in range(i, len(self) - 1): self._items[j] = self._items[j + 1] self._size -= 1 self.incModCount() # Track mutations! return item

The ListIterator Class class ArrayList(AbstractList): """Represents an array-based list.""" def listIterator(self): """Returns a list iterator.""" return ArrayList.ListIterator(self) Because the ListIterator will be implemented differently for each list implementation, we can nest it in the list class

The ListIterator Class class ArrayList(AbstractList): """Represents an array-based list.""" def listIterator(self): """Returns a list iterator.""" return ArrayList.ListIterator(self) class ListIterator(object): """Represents the list iterator for an array list.""" def __init__(self, backingStore): self._backingStore = backingStore self._modCount = backingStore.getModCount() self.first() def first(self): """Returns the cursor to the beginning.""" self._cursor = 0 self._lastItemPos = -1 # Other ListIterator methods go here

The next Method class ListIterator(object): """Represents the list iterator for an array list.""" def next(self): """Preconditions: hasNext returns True The list has not been modified except by this iterator's mutators. Returns the current item and advances the cursor to the next item."" if not self.hasNext(): raise ValueError("No next item in list iterator") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store") self._lastItemPos = self._cursor self._cursor += 1 return self._backingStore[self._lastItemPos]

Moving from Right to Left def last(self): """Moves the cursor to the end of the backing store.""" self._cursor = len(self._backingStore) self._lastItemPos = -1 def hasPrevious(self): """Returns True if the iterator has a previous item or False otherwise.""" return self._cursor > 0 def previous(self): """Preconditions: hasPrevious returns True The list has not been modified except by this iterator's mutators. Returns the current item and moves the cursor to the previous item.""" if not self.hasPrevious(): raise ValueError("No previous item in list iterator") self._lastItemPos = self._cursor - 1 self._cursor -= 1 return self._backingStore[self._lastItemPos]

For Wednesday Sorted Lists