iterators - carnegie mellon school of computer sciencemrmiller/15-121/slides/23-iterators.pdf ·...

23
Iterators 15-121 Fall 2019 Margaret Reid-Miller

Upload: others

Post on 24-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Iterators

15-121 Fall 2019Margaret Reid-Miller

Page 2: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Today

• Comparators from last class• Iterators and the Iterator interface• ListIterator interface• Iterable interface and enhanced for loop• Two new Abstract Data Types:• Sets and Maps

• Their interfaces and uses

Fall 2019 15-121 (Reid-Miller) 2

Page 3: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Java sorts in "natural order"• In Arrays class:

public static void sort(Object[] items)• All objects must Comparable (compareTo).• Implemented with a modified merge sort in O(n log n)

– Adapted from sort used in Python (Tim’s sort)• Sort is stable

• In Collections class:public static <T extends Comparable<T>> void

sort(List<T> list)• Same conditions as above• Copies elements into an array and uses Arrays.sort

Fall 2019 15-121 (Reid-Miller) 3

Page 4: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Java sorts with other orderings

• In Arrays class:public static <T> void sort(T[] items,

Comparator<? super T> comp)• Another version allows a sort using a Comparator so

ordering can be done on some other property other than the items' natural ordering.

• For example: You might order strings not alphabetically, but instead by string length.

• comp must be an object that implements the Comparator interface for type T or a superclass of type T.

Fall 2019 15-121 (Reid-Miller) 4

Page 5: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Comparator Example

public class StringLengthCompimplements Comparator<String> {

public int compare(String s1, String s2) {return s1.length() - s2.length();

}}

Example:Assume s is an array of strings.

Arrays.sort(s);Arrays.sort(s, new StringLengthComp());

uses String's compareTo to sort s

uses StringLengthComp'scompare to sort s

Fall 2019 15-121 (Reid-Miller) 5

Page 6: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Iterators

Page 7: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Looping over a listpublic void traverse(List<String> list){

for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i) + “ “);

System.out.println();}

If the list has n elements, what is the order of complexity of this loop?

If list is an ArrayList? ________If list is a LinkedList? ________

O(n)O(n2)

Fall 2019 15-121 (Reid-Miller) 7

Page 8: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

List<E> methods includes iterator()int size()boolean add(E obj)void add(int index, E obj)E get(int index)…Iterator<E> iterator()

returns an iterator object that implements the Iterator<E> interface

Fall 2019 15-121 (Reid-Miller) 8

Page 9: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

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. (Can only be call once after calling next.)

Fall 2019 15-121 (Reid-Miller) 9

Page 10: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Print a list using an iteratorpublic static void print(List<String> list) {

Iterator<String> iter = list.iterator();

while (iter.hasNext()) {System.out.print(iter.next() + " ");

System.out.println();}

If the list has n elements, what is the order of complexity of this method? ______Somehow, the Iterator must remember which element is the next element, so can get it in O(1) time.

O(n) !

Fall 2019 15-121 (Reid-Miller) 10

Page 11: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Careful: What will this code print?public static void print(List<String> list) {

Iterator<String> iter = list.iterator();

while (iter.hasNext()) {if (it.next().equals("Hello")

System.out.print(iter.next() + " ");}Given ["Hello", "What's up?", "Bye"]?

It prints only "What's up" because each call to it.next() returns a different element.

Lesson: Call it.next() once per iteration (and perhaps store in a variable)

Fall 2019 15-121 (Reid-Miller) 11

Page 12: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Careful: What will this code do?public static void print(List<String> list) {

while (list.iterator().hasNext()) { System.out.print(list.iterator().next());

}

Prints first value in an infinite loop! Why?

Each call to list.iterator() returns a NEW Iterator that starts iterating from the beginning of the list.

Lesson: Call iterator once and store in a variable.

Fall 2019 15-121 (Reid-Miller) 12

Page 13: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Careful: What will this code do?public static void remove(List<String> list,

String s) {Iterator<String> iter = list.iterator();int index = 0;while (iter.hasNext()) {

if (it.next().equals(s))list.remove(index);

elseindex++;

}CRASHES with ConcurrentModificationException

Lesson: Don't modify the collection except by using the iterator's remove method.

Fall 2019 15-121 (Reid-Miller) 13

Page 14: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Use the iterator's remove method when using an iterator// Removes all occurrences of s from listpublic static void remove(List<String> list,

String s) {Iterator<String> iter = list.iterator();while (iter.hasNext()) {

if (it.next().equals(s))iter.remove(index);

}

What is the runtime complexity?ArrayList: _________LinkedList: _________

Fall 2019 15-121 (Reid-Miller) 14

O(n)O(n2)

Page 15: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Java ListIterator<E> interface• ListIterator is an extension of Iterator• Recall: The LinkedList class implements the List<E> interface using a doubly-linked list.

• Methods in LinkedList that return a list iterator:public ListIterator<E> listIterator()public ListIterator<E> listIterator(int index)

• Methods in the ListIterator interface:• add, hasNext, hasPrevious, next, previous,nextIndex, previousIndex, remove, set

Fall 2019 15-121 (Reid-Miller) 15

Page 16: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Example: Replace a value in a list

Replace the first occurrence of target in LinkedListlist of strings with newItem :

ListIterator<String> iter =list.listIterator();

while (iter.hasNext()) {if (target.equals(iter.next())) {

iter.set(newItem);break;

}}

NOTE: you can use set, add, remove only once after next() or previous()

Fall 2019 15-121 (Reid-Miller) 16

Page 17: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Example

• Count the number of times target appears in LinkedList list of strings :int count = 0;ListIterator<String> iter =

list.listIterator();while (iter.hasNext()) {

if (target.equals(iter.next())) {count++;

}}

Fall 2019 15-121 (Reid-Miller) 17

Page 18: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Example(using the enhanced for loop)

• Count the number of times target appears in LinkedList list of strings :int count = 0;for (String nextStr : list) {

if (target.equals(nextStr)) {count++;

}}

implicitly instantiates an iterator and calls the hasNext and next methods;remove is not available

Fall 2019 15-121 (Reid-Miller) 18

Page 19: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

The Iterable interface

• If we have SinglyLinkedList implements Iterator, we can only have one iterator for the list.• That is, the singly-linked list class acts as the iterator

itself.

• Instead, SinglyLinkedList can implement Iterable, which means that the class has an inner class that implements Iterator and each instance of this class is an iterator object.• We can have more than one iterator for a list.

Fall 2019 15-121 (Reid-Miller) 19

Page 20: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Iterable<T> interface

• Specifies an iterator method.Iterator<T> iterator()

• Implemented by the Collection interface.• All classes that implement the Collection interface

must include an iterator method that returns an Iterator for that collection.

• The enhanced for statement can then be used to "traverse" the collection one element at a time easily.

Fall 2019 15-121 (Reid-Miller) 20

Page 21: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Example(using the enhanced for loop)

• Let myList be an ArrayList of Integer.• Since myList is an ArrayList, and ArrayList is

a subclass of Collection, it must have an iterator method that returns an iterator for the collection.

int total = 0;for (int nextInt : myList)

total += nextInt;

Fall 2019 15-121 (Reid-Miller) 21

Page 22: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

Example(using the enhanced for loop)

• Enhanced for loops can also be used with arrays.int[] dataArray = new int[1000];...int total = 0;for (int nextInt : dataArray) {

total += nextInt;} no index

Fall 2019 15-121 (Reid-Miller) 22

Page 23: Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf · •Iterators and the Iterator interface •ListIteratorinterface •Iterableinterface

The Collection Hierarchy

Collection

Queue List AbstractCollection Set

AbstractList AbstractSet SortedSet

HashSet TreeSetVector ArrayList

Stack

AbstractSequentialList

LinkedList AAA

InterfaceAbstract ClassConcrete Class

extendsimplements

Iterable

Fall 2019 15-121 (Reid-Miller) 23