API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.



Similar documents
Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

D06 PROGRAMMING with JAVA

Class 32: The Java Collections Framework

Data Structures and Algorithms

Data Structures in the Java API

LINKED DATA STRUCTURES

The Java Collections Framework

Algorithms and Data Structures Written Exam Proposed SOLUTION

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Basic Programming and PC Skills: Basic Programming and PC Skills:

Binary Search Trees (BST)

CompSci-61B, Data Structures Final Exam

CS 111 Classes I 1. Software Organization View to this point:

DATA STRUCTURES USING C

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Introduction to Stacks

Binary Heap Algorithms

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Why Use Binary Trees?

Chapter 14 The Binary Search Tree

Ordered Lists and Binary Trees

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

dictionary find definition word definition book index find relevant pages term list of page numbers

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Data Structures and Algorithms Lists

Introduction to Programming System Design. CSCI 455x (4 Units)

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Analysis of a Search Algorithm

JAVA COLLECTIONS FRAMEWORK

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

cs2010: algorithms and data structures

Project 4 DB A Simple database program

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

4.5 Symbol Table Applications

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Data Structure [Question Bank]

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Binary Trees and Huffman Encoding Binary Search Trees

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

AP Computer Science AB Syllabus 1

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Binary Heaps. CSE 373 Data Structures

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Data Structures and Algorithms

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Computer Programming I

Java the UML Way: Integrating Object-Oriented Design and Programming

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 7: Sequential Data Structures

Using the Monitoring and Report Viewer Web Services

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

J a v a Quiz (Unit 3, Test 0 Practice)

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Software Engineering Techniques

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

PES Institute of Technology-BSC QUESTION BANK

Chapter 8: Bags and Sets

CSC 551: Web Programming. Fall 2001

Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)

Practical Session 4 Java Collections

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Graduate Assessment Test (Sample)

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

CMSC 202H. ArrayList, Multidimensional Arrays

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Stacks. Data Structures and Data Types. Collections

Binary Search Trees 3/20/14

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Java Software Structures

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Working with Java Collections

10CS35: Data Structures Using C

by LindaMay Patterson PartnerWorld for Developers, AS/400 January 2000

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Java Map and Set collections

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

ECE 122. Engineering Problem Solving with Java

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Transcription:

Sequences and Urns 2.7 Lists and Iterators Sequence. Ordered collection of items. Key operations. Insert an item, iterate over the items. Design challenge. Support iteration by client, without revealing the internal representation of the collection. next It was the best of times 2 Iterator Interface Iteration in Java API for java.util.iterator.! hasnext() Are there more items in the list?! next() Return the next item in the list.! remove() Delete the last item returned by next(). public interface Iterator<Item> { boolean hasnext(); Item next(); void remove(); // optional next It was the best of times 4

Iterator Client Iterable Interface API for java.util.iterator.! hasnext() Are there more items in the list?! next() Return the next item in the list.! remove() Delete the last item returned by next(). API for java.lang.iterable.! iterator() Return an iterator. Sequence<String> list = new Sequence<String>(); list.add("this"); list.add("is"); list.add("a"); list.add("test."); Iterator<String> i = list.iterator(); while (i.hasnext()) { String s = i.next(); System.out.println(s); public interface Iterable<Item> { Iterator<Item> iterator(); Ex. Sequence, java.util.arraylist, HashSet. 5 6 Enhanced For Loop Enhanced for loop. Syntactic sugar for iterating over a collection. Sequence ADT: Two Implementations Sequence<String> list = new Sequence<String>(); list.add("this"); list.add("is"); list.add("a"); list.add("test."); for (String s : list) System.out.println(s); implements Iterable! can iterate using enhanced for loop Remark. Can also use enhanced for loop with arrays. 7

Sequence: Linked List Implementation Sequence: Linked List Implementation (cont) import java.util.iterator; import java.util.nosuchelementexception; private class SeqIterator implements Iterator<Item> { Node current = first; public class Sequence<Item> implements Iterable<Item> { private Node first, last; private class Node { Item item; Node mext; public void add(item item) { Node x = new Node(); x.item = item; if (first == null) first = x; else last.next = x; last = x; public Iterator<Item> iterator() { return new SeqIterator(); next slide same as queue public boolean hasnext() { return current!= null; public void remove() { throw new UnsupportedOperationException(); public Item next() { if (!hasnext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; current It was the best of times 9 10 Sequence: Array Implementation Sequence: Array Implementation (cont) import java.util.iterator; import java.util.nosuchelementexception; private class SeqIterator implements Iterator<Item> { int i = 0; public class Sequence<Item> implements Iterable<Item> { private Item[] a = (Item[]) new Object[8]; private int N = 0; public void add(item item) { if (N >= a.length) resize(); a[n++] = item; public Iterator<Item> iterator() { return new SeqIterator(); as usual, with array doubling public boolean hasnext() { return i < N; public void remove() { throw new UnsupportedOperationException(); public Item next() { if (!hasnext()) throw new NoSuchElementException(); return a[i++]; private class SeqIterator // see next slide i It was the best of times N 0 1 2 3 4 5 6 7 11 12

Load Balancing Applications Load balancing. N users want to choose among N identical file shares. The goal is to balance users across file shares. Assume it's too hard to coordinate (or query) all resources to see how empty they are. Random assignment. Assign each user to a resource at random. % java LoadBalance 10 0: 1: 2: user7 3: user1 user2 user8 4: user0 user9 5: 6: user3 user6 7: 8: user4 9: user5 max load = 3 14 Server.java Load Balancing public class Server { private Sequence<String> list = new Sequence<String>(); private int load; public void add(string user) { list.add(user); load++; public String tostring() { String s = ""; for (String user : list) s += user + " "; return s; public class LoadBalance { int N = Integer.parseInt(args[0]); Server[] servers = new Server[N]; for (int i = 0; i < N; i++) servers[i] = new Server(); // assign N users to N servers at random for (int j = 0; j < N; j++) { String user = "user" + j; int i = (int) (Math.random() * N); servers[i].add(user); // print results for (int i = 0; i < N; i++) System.out.println(i + ": " + servers[i]); 15 16

Load Balancing Java List Libraries: ArrayList and LinkedList Load balancing. N users want to choose among N identical file shares. The goal is to balance users across file shares. Assume it's too hard to coordinate (or query) all resources to see how empty they are. API for java.util.arraylist.! add() Add item to end of list.! iterator() Return an iterator to the list.! size(), remove(), set(), clear(), indexof(), toarray(),. Coordinated assignment. Assign user i to server i. Result. Max load = 1. Random assignment. Assign each user to a resource at random. Theory. Max load " log N / log log N. Best of two. For each user, choose two resources at random and assign user to least busy one. Theory. Max load " log log N. import java.util.arraylist; public class Test { ArrayList<String> list = new ArrayList<String>(); list.add("this"); list.add("is"); list.add("a"); list.add("test."); for (String s : list) System.out.println(s); 17 18 Binary Tree Iterator Tree Iterators Binary tree. Create an iterator for a binary tree. (and avoid using extra space) M public class BinaryTree<Item> { private Node root; E T private class Node { Item item; Node l, r; B H P V W Y public Iterator<Item> iterator() { return new Preorder(); goal: implement this 20

Preorder Traversal Binary Tree Iterator: Preorder Traversal Preorder traversal. Visit a node before its two children. private class Preorder implements Iterator<Item> { Stack<Node> stack = new Stack<Node>(); private static void preorder(node x) { if (x == null) return; System.out.println(x.item); preorder(x.l); preorder(x.r); B E H M P T W Preorder() { if (root!= null) stack.push(root); public void remove() { // throw exception as before public boolean hasnext() { return!stack.isempty(); Q. How to implement an iterator for preorder traversal? V Y preorder: M E B H T P W V Y public Item next() { if (!hasnext()) throw new NoSuchElementException(); Node x = stack.pop(); Item item = x.item; if (x.r!= null) stack.push(x.r); if (x.l!= null) stack.push(x.l); return item; 21 22 Binary Tree Iterator: Level Order Level order. Examine nodes in order of distance from root. Q. How to implement an iterator for level order traversal? M E T B H P W V Y level order: M E T B H P W V Y 23