Iterators - Carnegie Mellon School of Computer Sciencemrmiller/15-121/Slides/23-Iterators.pdf ·...

Post on 24-Jun-2020

1 views 0 download

transcript

Iterators

15-121 Fall 2019Margaret Reid-Miller

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

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

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

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

Iterators

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

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

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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