Lecture 8: Iterators and More Mutation

Similar documents
Lecture 7: Implementing Lists, Version 2

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Lecture 16: HashTables 10:00 AM, Mar 2, 2018

Lecture 7: Lists, Version 2 (with Mutation)

Homework 2: Imperative Due: 5:00 PM, Feb 16, 2018

Lecture 5: Implementing Lists, Version 1

Intro. Scheme Basics. scm> 5 5. scm>

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

CS 3 Introduction to Software Engineering. 5: Iterators

CS261 Data Structures. Iterator ADT Dynamic Array and Linked List

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

Lecture 17: Implementing HashTables 10:00 AM, Mar 5, 2018

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

CS261 Data Structures. Iterator ADT Dynamic Array and Linked List

Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018

Lecture 11: In-Place Sorting and Loop Invariants 10:00 AM, Feb 16, 2018

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

ITI Introduction to Computing II

ITI Introduction to Computing II

ITI Introduction to Computing II

ITI Introduction to Computing II

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018

Outline. iterator review iterator implementation the Java foreach statement testing

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Java Comparable interface

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

2IP15 Programming Methods

Computer Science E-119 Fall Problem Set 4. Due prior to lecture on Wednesday, November 28

Types, Expressions, and States

JAVA COLLECTION FRAMEWORK & SETS

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Lecture 11: Recursion (hard)

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Lecture 4: Inheritence and Abstract Classes

Lecture 23: Priority Queues 10:00 AM, Mar 19, 2018

Lecture Transcript While and Do While Statements in C++

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

[TAP:PMUHE] Stack vs Queue

Lab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018

The Design Recipe Fall 2017

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Java Review: Objects

Programming II (CS300)

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

TREES. Tree Overview 9/28/16. Prelim 1 tonight! Important Announcements. Tree terminology. Binary trees were in A1!

Recursive Objects. Singly Linked List (Part 2)

Lecture 24: Implementing Heaps 10:00 AM, Mar 21, 2018

Lecture 28: Graphs: Shortest Paths (Part 1)

Lecture 23: Priority Queues, Part 2 10:00 AM, Mar 19, 2018

CS1102: Macros and Recursion

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

Project Compiler. CS031 TA Help Session November 28, 2011

Lecture 23: Priority Queues, Part 2 10:00 AM, Mar 19, 2018

CS 61B Discussion 5: Inheritance II Fall 2014

Higher-Order Sequential Operations

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

TREES Lecture 12 CS2110 Fall 2016

Compiler Design Spring 2017

COMP 161 Lecture Notes 16 Analyzing Search and Sort

CMPSCI 187 / Spring 2015 Implementing Sets Using Linked Lists

Good Coding Practices Spring 2018

Chapter 4 Defining Classes I

CS11 Java. Winter Lecture 8

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

B-Trees. Based on materials by D. Frey and T. Anastasio

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Chapter 10 Recursion

Java Map and Set collections

Loops. CSE 114, Computer Science 1 Stony Brook University

Comp215: More lists. Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved.

Linked Lists. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Homework 5: Fun with Scala Due: 5:00 PM, Mar 16, 2018

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

CMSC 341 Lecture 7 Lists

Defining Your Own Classes

The Design Recipe Fall 2018

1 ICS 161: Design and Analysis of Algorithms Lecture notes for January 23, Bucket Sorting

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree:

Section 05: Solutions

CITS1001 week 4 Grouping objects lecture 2

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Transcription:

Integrated Introduction to Computer Science Fisler, Nelson Contents 1 Traversing Lists 1 2 Motivating Iterators 2 3 Writing an Iterator 3 4 Writing Sum with an Iterator 4 Objectives By the end of this lecture, you will know: ˆ How to allow iteration over a list without exposing implementation details By the end of this lecture, you will be able to: ˆ Write a while loop to traverse a data structure in Java ˆ Implement an iterator for your LinkedList class 1 Traversing Lists Let s support some common methods on lists. We ll start with size, assuming that we prefer to save the space of a size field, and instead write a method to traverse the list and compute the size each time someone asks for it. We could proceed recursively, starting from the first Node and continuing until null. However, Java also allows us to work iteratively. A while statement (also caled a while loop) repeats the code inside it until its condition is false. Here is the skeleton of how we might write size iteratively: public int size() { Node current = start; return 0; //??? When we say Node current = start at the beginning of the method, Java creates a new name, current, that refers to whatever Node object start points to at that moment. If the list is empty,

current will contain null and the while loop will never run. Then the method will return zero, which is what we d expect. If the list is not empty, Java populates current with a reference to the first Node. This isn t equal to null, so Java runs the loop body. Each time the loop body runs, current advances one step along the list, and the loop continues to run until current falls off the end of the list (i.e., is set to null). This current =... business looks exactly like what we ve previously seen with creating and mutating object fields. The difference is that the name current is not a field, but a local variable. It belongs to the method, and only lasts as long as the method does. Java won t understand if you try to talk about current outside of the size method. There s still a problem, though. How do we return the correct value for a non-empty list? We just add another local variable to store a count of how many Nodes get visited. Each iteration of the loop, we increase count by one: public int size() { Node current = start; int count = 0; count = count + 1; return count; And that s it. Every time the current reference advances, the count goes up by one, until we run out of Nodes and return how many were seen. 2 Motivating Iterators Let s try something a bit more complicated. Suppose that we want to write a method outside the LinkedList class! that takes in a list of integers and returns the sum of all elements in the list. You ve done similar things before in CS 17 you d just fold addition over the list. How can we do the same thing iteratively? We might imagine adapting the while loop we wrote for size, producing something like this: public int sum(linkedlist<integer> lst) { Node current = lst.start; int s = 0; s = s + current.item; return s; But it s better not to. One of the principles of good Object-Oriented design is that external code shouldn t need to be aware of, let alone use, internal implementation details. If we write sum 2

this way, we re assuming that the list we receive is in fact a LinkedList. We d like to write a sum method that works for any class that implements IList, no matter how it s implemented. This means that using the next field is off the table. Ok, but how do we iterate over the list if we can t access the next field, or even trust that there s an inner Node class at all? The answer is that external users of LinkedList can t! At least not without a bit of extra help inside LinkedList. 3 Writing an Iterator First, let s figure out which parts of the above badly-designed sum method really belong in sum, and which in the LinkedList class. The lines where we create and add to the s variable are purpose-specific: they re all about summing over integers. So we ll keep them in the sum method. But what about current? It only exists to facilitate iterating over a list with this particular implementation. So we ll have to move it into the LinkedList class somehow. Should we make current a field of LinkedList? No! If we did that, a LinkedList could only support one iteration at a time multiple external methods (say sum and a max method that keeps the highest value in the list) would always be looking at the same position in the list. Even more, they d have to manually reset the field when they were done. Instead, we need to somehow provide the essence of current to many different external callers. To do so, we ll allow any external method to obtain what s called an iterator from a LinkedList. Each iterator keeps track of how far into the list it s currently looked. We ll add the iterator as another inner class within LinkedList, LinkedListIterator. Iterators provide two methods: hasnext, which returns true if the iterator has not run out of elements to return, and next, which returns the next element and advances. Java provides a built-in Iterator interface that enforces those two methods exist. Finally, the new constructor accepts a particular LinkedList to start iterating over. class LinkedListIterator implements Iterator<T> { Node current; public LinkedListIterator(LinkedList<T> thelist) { this.current = thelist.getstart(); @Override public boolean hasnext() { return (this.current!= null); @Override public T next() { T item = this.current.item; this.current = this.current.next; return item; We ll also had a method to the LinkedList class that manufactures an iterator for external use. 3

public Iterator<T> iterator() { return new LinkedListIterator(this); Even better, we ll modify the IList interface so that every list must provide an iterator method. (Again, Java provides a built-in interface to enforce this, called Iterable.) public interface IList<T> extends Iterable<T> { public void addfirst(t newitem); public void addlast(t newitem); public T getfirst(); public Iterator<T> iterator(); 4 Writing Sum with an Iterator Finally, we can write sum in proper Object-Oriented style. All our sum method has to do is obtain an iterator and accumulate the integers it returns. Even better, it no longer has to know for sure that it is being given a LinkedList just that it is some class that implements IList<Integer>. public int sum(ilist<integer> lst) { Iterator<Integer> iter = lst.iterator(); int s = 0; while (iter.hasnext()) { s = s + iter.next(); return s; Java has some syntax that makes this style of loop even easier. You can use a for loop to automatically iterate over any collection (more on this word later) that provides an iterator (i.e., implements the Iterable interface). public int sum(ilist<integer> L) { int sum = 0; for(integer avalue : L) { sum = sum + avalue; return sum; The for loop syntax creates a new local variable avalue and, for each item in L, it populates avalue with what the iterator returns and executes the body. Note that this local variable is even shorter-lived than the ones we used earlier in this lecture: the name only exists within the loop itself! 4

Iterators are an elegant way to expose the contents of a list to outside code without exposing implementation details. We ll soon see several new reasons why this is important. Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS18 document by filling out the anonymous feedback form: http://cs.brown.edu/ courses/cs018/feedback. 5