Need to access each element of a list. Use index to access an element of the list. It s quadratic, while:

Size: px
Start display at page:

Download "Need to access each element of a list. Use index to access an element of the list. It s quadratic, while:"

Transcription

1 ! " # $ $ % & ' () * + (, -. /* 0 * / ( ' 7 8 * / 9 : ; < 8 * /' 8 - /4 J K L M N O PQ M R S After studying this chapter you should understand the following: the role of iterators in container classes; various implementations of the Iterator interface; iterators as an abstraction of indexes in list operations; the notion of an internal iterator; S the basic structure of the java.util.collection hierarchy. Also, you should be able to: use iterators in algorithms dealing with lists; define a class that provides a new implement of the Iterator interface. >?@ABCDEFG HI = V N N M R R PW X Y PR O M YM Z M W O R S Need to access each element of a list. S Use index to access an element of the list. for array-based implementations: get(i) is constant. for linked implementations: get(i) is linear. for (int i = 0; i < list.size(); i = i+1) do something with list.get(i); S It s quadratic, while: int i = list.indexof(element); list.remove(i); S both statements linear for a linked implementation. S Need: Reduce cost of linked-list traversals. >?@ABCDEFG HI U >?@ABCDEFG HI [

2 It s object associated with container that sequentially accesses each element in the container. nhutilites.containers2 contains classes described. he standard package java.util includes a different interface also named Iterator<E>. public interface Iterator<Element> extends Cloneable Iterator for accessing and traversing elements of a container. public void reset () Initialize this Iterator to reference the first element. public void advance () Advance this Iterator to the next element. require:!this.done() public boolean done () No more elements to traverse in the container. public Element get () Element this Iterator currently references. require:!this.done() public boolean equals (Object obj) he specified Object is an Iterator of the same class as this, and references the same relative element of the same container. Assume container c, and i an iterator for it. Can access each element in container as follows: public boolean traverses (Object container) his Iterator traverses the specified container. public Object clone () A copy of this Iterator. public void setequalo (Iterator<Element> other) Set this Iterator to reference the same container element as the specified Iterator. Both Iterators must traverse the same container. require: ensure: this.traverses(container) implies other.traverses(container) this.equals(other) i.reset(); while (!i.done()) { do something with i.get(); i.advance(); Example: o see if element is in container: i.reset(); while (!i.done() &&!i.get().equals(element)) i.advance();

3 int ' ( ) * + (, * -. / 0). ) 1 ( + ( -, 1 2 An index int variable is a simple for of iterator: It is reset by setting variable to 0. Advanced by incrementing variable. It is done when variable equals the length of the list. Every iterator implementation is coupled to its container. «interface» Iterator<Element> ListIterator<Element> LinkedList<Element>.Iterator DoublyLinkedList<Element>.Iterator!"#$ %& : 8 ; : < = > 9? A B C D7 B 7 E A: E? : 8 ; : < = > 9? A B C D7 B 7 E A: E? public class ListIterator<Element> implements Iterator<Element> { private int current; // index into thelist private List<Element> thelist; // the List this Iterator references /** * Create a new iterator for the specified List. */ public ListIterator (List<Element> list) { thelist = list; current = 0;!"#$ %& 34 //Initialize this Iterator to reference the first public void reset () { current = 0; //Advance this Iterator to next element. public void advance () { current = current + 1; //No more elements to traverse in the container. public boolean done () { return current >= thelist.size(); //Container element this Iterator currently references. public Element get () { return thelist.get(current);!"#$ %& 33

4 -. / / 8 9 5:. : Define an iterator for LinkedList<Element> as a private inner class. It can then directly access implementation structure of the LinkedList and of component Nodes. It keeps a reference to Node containing current element. private class Iterator implements nhutilities.containers.iterator<element> { private Node current; //Create a new Iterator for this LinkedList public Iterator () { reset(); //Initialize this Iterator to reference the first element. public void reset () { current = LinkedList.this.first; //Advance this Iterator to next element. public void advance () { current = current.next;! "#$ %&'()* +, -. / / 8 9 5:. : = 0 / > 5. / : 3 2 0? / 0 : //No more elements to traverse in the container. public boolean done () { return current == List<Element> includes method for creating an iterator //Container element this Iterator currently references. public Element get () { return current.element; public Iterator<Element> iterator () Create a new Iterator for this List.! "#$ %&'()* +, ;! "#$ %&'()* +, <

5 ! " #$ % $ & ' #% ( ) ' #* " +, -. % " / #"! " $ * AbstractList<Element> creates ListIterator<Element> as a default iterator. public abstract class AbstractList<Element> implements List<Element> { public Iterator<Element> iterator () { return new ListIterator<Element>(this); his default implementation is only good for arraybased implementations. 0 he class LinkedList<Element>, 1 overrides iterator() method and returns an instance of AB C D E FG H G I C J K AC L M C G N O C P N Q O N O H G C G N AB C D E FG H G I C J K AC L M C G N O C P N Q O N O H G C G N B R We d like to be able to delete the element identified by an iterator, change it, insert an element in front of it, etc. R Overload List<Element> methods that take index arguments with methods taking iterator arguments :;<= >? 23 public Element get (Iterator<Element> iterator) he Element referenced by the specified Iterator. public Iterator<Element> iteratorat (Element element) An Iterator referencing the first occurrence of the specified Element in this List<Element>; Iterator<Element> is done if not found. public void add (Iterator<Element> iterator, Element element) Insert the specified Element at the specified position. he Iterator will reference the newly added Element. public void remove (Iterator<Element> iterator) Remove the Element at specified position. Iterator will reference Element following removed Element. If no Element follows the removed Element (i.e., the removed Element was last in this List), iterator.done() is true. public void set (Iterator<Element> iterator, Element element) Replace the element at the specified position with the specified Element. U VWX YZ[\]^ _` S

6 M H Q N P AI M C G N O C P N P AB C B M H Q N P AI M C G N O C P N P AB C B R LinkedList<Element>.Iterator references current node of a LinkedList<Element> R Sufficient to implement get and set. R o implement remove and add, need reference to Node preceding current Node. R Must traverse list to find needed Node. R o solve problem: keep a pair of references in the iterator, one to the current Node and one to the preceding Node. Or keep a reference to the Node preceding current one. In either case, it will simplify things if a LinkedList<Element> has a header U VWX YZ[\]^ _` U VWX YZ[\]^ _` S! " # $ % & # ' ( # ) * # ) " It is possible to move forward or backward through a doubly linked list as each node contains forward and backward references. Define an Iterator<Element> extension that permits forward and backward traversal of a list, and ensure that a DoublyLinkedList<Element> creates such an iterator., ) - # * ( # ) * # ) $ % & # ' public interface BiDirectionalIterator<Element> extends Iterator<Element> public boolean done () his Iterator has been advanced past the last element, backed up past the first element, or the container is empty. Equivalent to offright() offleft(). public boolean offright () his Iterator has been advanced past the last element, or the container is empty. public boolean offleft () his Iterator has been backed up past the first element, or the container is empty. public void advance () Move this Iterator forward to the next element. If this.offleft() and the container is not empty, move to the first element. public void backup () Move this Iterator back to the previous element. If this.offright() and the container is not empty, move to the last element. require!this.offleft() +

7 -. / : What is the state of an iterator when a node is deleted via the iterator? Example: iterator i = list.iterator(); while(!i.done()){ if condition(i.current()) list.remove(i); i.advance(); wo questions: What node (if any) should I reference after the deletion? How should other iterators on same list behave? ; What node (if any) should I reference after the deletion? It should not refer to the node containing the element deleted. It should not refer to the next element down the list, as that element would not be processed. ; hen to what? It should be set to null Methods current(), and advance() must be modified to handle this situation! "#$ %&'()* +, -. / : / : ; We assume that the list has a header and that iterator has a reference to current, and previous node. public void advance(){ if (current == null) current = previous.next; else current = current.next; ; We assume that the list has a header and that iterator has a reference to current, and previous node. public void remove(iterator i){ previous.next = current.next; current = null;! "#$ %&'()* +, <! "#$ %&'()* +, =

8 how an Iterator behaves if the List is modified by means of another Iterator, or by means of an index. For instance, suppose i and j are distinct Iterator instances referencing the same element List<Element> list a b c d e f Iterator i Iterator j Executing list.remove(j); or list.remove(2); what will the state of the i iterator be?. / / / : 8 ; 2 / / >. / / 3 1 4? : 3 2 ; A B 3 < If a List is modified via an index, all Iterators that reference the List become invalid. < Furthermore, if a List is modified by an Iterator, all other Iterators that reference the List become invalid. < client provides an operation and iterator itself applies operation to each container element. < hey support performing some specific operation on each item in the container. < We consider adding this feature to the List interface. < he operation to be performed should be provided as a method argument, encapsulated in an object. " #$% &'()*+,-! " #$% &'()*+,- =

9 We define an interface to model an operation: Using an Iterator method can be implemented in public void execute (Element element) he operation. AbstractList<Element> : public interface Operation<Element> An operation that can be preformed on an Element. Method foreachdo has an Operation parameter: /** * Perform the specified Operation on each element * of this List. */ public void foreachdo (Operation<Element> operation); public void foreachdo (Operation<Element> operation) { Iterator<Element> iterator = this.iterator(); iterator.reset(); while (!iterator.done()) { operator.execute(iterator.get()); iterator.advance();! "# " " For example, suppose roll is a List<Student> and want to add ten points to each Student s grade: roll.foreachdo( new Operation<Student> () { public void execute(student element) { element.setgrade(element.getgrade() + 10); ); foreachdo allow to perform an operation on each list element. It does not allow to replace elements. Nor to query list for a value that requires querying each element. Handling such problems requires more structure.

10 # "! " A B C B DE F GH I J K K L M N O J P Q R K L S L P N U VW X Y X Z U [ - $ (. / '$ & ' '( ) * + (, $ %!" # $ % \ Java package java.util defines a set of interfaces and classes rooted at interface Collection<Element>. \ his hierarchy contains members closely related to classes and interfaces described in this chapter. \ he library available since Java 1.2, and retrofitted for type parameters in Java 1.5. \ Collection ] models a generalized container. ] Some Collections allow duplicate elements, others do not. Some Collections impose an ordering on the elements; some are unordered :; <= 01 l m n o p q p rs t uv w x y y z { x ~ y z z ~ m un ƒ p ƒ m l m n o p q p rs t uv w x y y z { x ~ y z z ~ m un ƒ p ƒ m Collection methods include: public boolean contains (Element e) his collection contains the specified element. pubic boolean isempty() his collection contains no elements. public int size () he number of elements in this collection. public java.util.iterator iterator() An iterator over the elements in this collection. Operations add and remove elements are optional. An implementing class can choose to support them or not. public boolean add (Element element) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException ` abcdefghi jk ^_ List extends Collection. his interface models a sequential collection in which elements can be accessed by index. A List can contain duplicate elements, but operations to add and remove elements are still specified as optional. java.util.set extends Collection and specifies a Collection that does not contain duplicate elements. Classes AbstractCollection, AbstractList, and AbstractSet. hese classes provide skeletal implementations of the interfaces. Concrete implementation classes extend these abstract classes. ` abcdefghi jk ˆ

11 ! " # $! % & & ' ( : ; < = >? B CD E F G G H I J K F L M N G H O H L J P Q RS U V Q W ) Array-based list implementations extending AbstractList * Java.util.ArrayList * java.util.vector. + Array-based implementations grow automatically. + java.util.linkedlist extends AbstractSequentialList, «interface» Collection<Element> «interface» List<Element> AbstractCollection<Element> AbstractList<Element> AbstracListElement> Vector<Element> which extends AbstractList. * It provides a doubly-linked list implementation. * Its iterator() method returns an iterator that allows bidirectional traversal of the linked list. AbstractSequentialList<Element> LinkedList<Element>. / ,- f g h i j g k i lm g h i n j o h ƒ ƒ ˆ p Interface Iterator<Element> specifies three methods: public boolean hasnext () he iteration has more elements.next public Element next () throws NoSuchElementException he next element in the iteration. hrows NoSuchElementException if hasnext() is false public void remove () throws UnsupportedOperationException, IllegalStateException Removes from the underlying collection the last element returned by the iterator (optional operation). his method can be called only once per call to next. Z [\]^_`abc de XY p Query hasnext is essentially the converse of our Iterator method done. p Note that method next is not a proper query since it changes the state of the iterator. p We could implement next by accessing the current element and then advancing the iterator: public Element next () { Element temp = this.get(); this.advance(); return temp; s tuvwxyz{ ~ qr

12 ƒ ƒ ˆ p ListIterator<Element> extends Iterator<Element>. p With a ListIterator, can traverse a list in either direction, can modify the list during iteration. It includes a method previous that serves as a companion to next, and optional methods for adding, removing, and setting list elements. s tuvwxyz{ ~ qq

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

Linked List Nodes (reminder)

Linked List Nodes (reminder) Outline linked lists reminders: nodes, implementation, invariants circular linked list doubly-linked lists iterators the Java foreach statement iterator implementation the ListIterator interface Linked

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

2. The actual object type stored in an object of type CollectionClassName<E> is specified when the object is created.

2. The actual object type stored in an object of type CollectionClassName<E> is specified when the object is created. 1. Because an ArrayList is an indexed collection, you can access its elements using a subscript. 2. The actual object type stored in an object of type CollectionClassName is specified when the object

More information

An Introduction to Data Structures

An Introduction to Data Structures An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use

More information

CS 3 Introduction to Software Engineering. 5: Iterators

CS 3 Introduction to Software Engineering. 5: Iterators CS 3 Introduction to Software Engineering 5: Iterators Questions? 2 PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One

More information

EECS 2011 M: Fundamentals of Data Structures

EECS 2011 M: Fundamentals of Data Structures EECS 2011 M: Fundamentals of Data Structures Suprakash Datta Office: LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle S. Datta (York Univ.) EECS 2011 W18 1 / 19 Iterators and

More information

Implementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC

Implementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC Implementing a List in Java CSC 143 Java List Implementation Using Arrays Updated with Java 5.0 Generics Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked

More information

Class 26: Linked Lists

Class 26: Linked Lists Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many

More information

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

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 Iterators 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 9-2 2-2 What is an Iterator? An iterator is an abstract data

More information

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework Announcements Abstract data types (again) PS 5 ready Tutoring schedule updated with more hours Today s topic: The Java Collections Framework Reading: Section 7.5 An ADT is a model of a collection of data

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

Introduction to Computer Science II (ITI 1121) Final Examination

Introduction to Computer Science II (ITI 1121) Final Examination Université d Ottawa Faculté de génie École d ingénierie et de technologie de l information University of Ottawa Faculty of Engineering School of Information Technology and Engineering Introduction to Computer

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Introduction to Computing II (ITI 1121) Final Examination

Introduction to Computing II (ITI 1121) Final Examination Université d Ottawa Faculté de génie École de science informatique et de génie électrique University of Ottawa Faculty of Engineering School of Electrical Engineering and Computer Science Introduction

More information

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

Computer Science CS221 Test 4 Name

Computer Science CS221 Test 4 Name Computer Science CS221 Test 4 Name 1. We looked at two different concrete classes that implemented the Queue interface, QueueAr which used an array as the underlying data structure, and QueueLi which used

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 26, 2013 Abstract These lecture notes are meant to be looked

More information

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 22 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Lecture 8: Iterators, Maps, and Hashtables Exercises 1. Show how to print out the elements of a doubly linked list in reverse order. 2. What are the Java API classes that

More information

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

Active Learning: Streams

Active Learning: Streams Lecture 29 Active Learning: Streams The Logger Application 2 1 Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CMSC 132, Object-Oriented Programming II Summer Lecture 9: CMSC 132, Object-Oriented Programming II Summer 2018 Lecturer: Anwar Mamat Lecture 9: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 9.1 QUEUE

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Iterators. Chapter 15. Copyright 2012 by Pearson Education, Inc. All rights reserved

Iterators. Chapter 15. Copyright 2012 by Pearson Education, Inc. All rights reserved Iterators Chapter 15 Contents What Is an Iterator? The Interface Iterator Using the Interface Iterator A Separate Class Iterator An Inner Class Iterator A Linked Implementation An Array-Based Implementation

More information

BlockingArrayQueue.java. Page 1

BlockingArrayQueue.java. Page 1 1 //BlockingArrayQueue.java 2 //Template blocking queue class, implemented with emulated circular array. 3 //Programmer: Randy Miller 4 //Last modification: April 13, 2015 5 6 7 8 import java.util.arraylist;

More information

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12 CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can

More information

CS 314 Exam 1 Spring 2015

CS 314 Exam 1 Spring 2015 Points off 1 2A 2B 3 4 Total off Net Score CS 314 Exam 1 Spring 2015 Your Name Your UTEID Instructions: 1. There are 4 questions on this test. 75 points available. Scores will be scaled to 150 points.

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 24, 2013 Abstract These lecture notes are meant to be looked

More information

Lists. The List ADT. Reading: Textbook Sections

Lists. The List ADT. Reading: Textbook Sections Lists The List ADT Reading: Textbook Sections 3.1 3.5 List ADT A list is a dynamic ordered tuple of homogeneous elements A o, A 1, A 2,, A N-1 where A i is the i-th element of the list The position of

More information

Basic Data Structures

Basic Data Structures Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1

More information

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList This article discusses the main classes of Java Collection API. The following figure demonstrates the Java Collection framework. Figure

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

Linked Lists. Linked List Nodes. Walls and Mirrors Chapter 5 10/25/12. A linked list is a collection of Nodes: item next -3.

Linked Lists. Linked List Nodes. Walls and Mirrors Chapter 5 10/25/12. A linked list is a collection of Nodes: item next -3. Linked Lists Walls and Mirrors Chapter 5 Linked List Nodes public class Node { private int item; private Node next; public Node(int item) { this(item,null); public Node(int item, Node next) { setitem(item);

More information

Lab 5 Random numbers!

Lab 5 Random numbers! Lab 5 Random numbers! ADT:s as Programming Tools! D0010E! Lecture 13! Iterators! MasterMind Reminder: Groups must have their designs approved before any actual programming is allowed to start. Some review

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

CISC 3115 TY3. C24a: Lists. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/15/2018 CUNY Brooklyn College

CISC 3115 TY3. C24a: Lists. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/15/2018 CUNY Brooklyn College CISC 3115 TY3 C24a: Lists Hui Chen Department of Computer & Information Science CUNY Brooklyn College 11/15/2018 CUNY Brooklyn College 1 Outline Concept of data structure Use data structures List Stack

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

More information

Recursive Objects. Singly Linked List (Part 2)

Recursive Objects. Singly Linked List (Part 2) Recursive Objects Singly Linked List (Part 2) 1 Operations at the head of the list operations at the head of the list require special handling because there is no node before the head node 2 Adding to

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 26, 2013 Abstract These lecture notes are meant to be looked

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1 Abstract Data Types Add Client Prog Rem Find Data Str. Show 01/30/03 Lecture 7 1 Linear Lists It is an ordered collection of elements. Lists have items, size or length. Elements may have an index. Main

More information

List ADT. B/W Confirming Pages

List ADT. B/W Confirming Pages wu3399_ch8.qxd //7 :37 Page 98 8 List ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the List ADT. the List ADT using an array

More information

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework SUMMARY COLLECTIONS FRAMEWORK PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 Introduction Collections and

More information

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST)

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) Preliminaries In this lab you will implement a binary search tree and use it in the WorkerManager program from Lab 3. Start by copying this

More information

Notes on access restrictions

Notes on access restrictions Notes on access restrictions A source code file MyClass.java is a compilation unit and can contain at most one public class. Furthermore, if there is a public class in that file, it must be called MyClass.

More information

Segments Proofs Reference

Segments Proofs Reference Segments Proofs Reference Properties of Equality Addition Property Subtraction Property Multiplication Property Division Property Distributive Property Reflexive Property The properties above may only

More information

Yes, it changes each time simulateonestep is invoked.

Yes, it changes each time simulateonestep is invoked. Exercise 10.1 Yes, the number of foxes changes. However, note that although this has a high probability of happening, it is not guaranteed to and will ultimately depend upon the initial state of the simulation.

More information

CMSC 206: Data Structures Final Exam Reference May 2018

CMSC 206: Data Structures Final Exam Reference May 2018 CMSC 206: Data Structures Final Exam Reference May 2018 public interface BMCSet /** Adds a new item to the set * @param item The new item to add to the set * @return true if the item is a new item added

More information

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

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes. CS231 - Spring 2017 Linked Lists List o Data structure which stores a fixed-size sequential collection of elements of the same type. o We've already seen two ways that you can store data in lists in Java.

More information

Collections. James Brucker

Collections. James Brucker Collections James Brucker Collection A Collection is a group of objects. Set an unordered collection no duplicates List ordered collection duplicates are allowed can add or remove elements anywhere in

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d)

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d) CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Inner Classes & Iterators Mar. 6, 2007 Inner Classes Classes can be nested inside other classes These are called inner classes Within

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

CSCI 200 Lab 3 Using and implementing sets

CSCI 200 Lab 3 Using and implementing sets CSCI 200 Lab 3 Using and implementing sets In this lab, you will write a program that manages a set of workers, using the Worker hierarchy you developed in Lab 2. You will also implement your own version

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 07: Linked Lists and Iterators MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Linked Lists 2 Introduction Linked List Abstract Data Type General Implementation of the ListADT

More information

Data Structure: Lists and Iterators. Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering

Data Structure: Lists and Iterators. Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering Data Structure: Lists and Iterators 2017 Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering Contents Data structures to be covered in this lecture Array lists (aka Vectors) Node lists

More information

JCF: user defined collections

JCF: user defined collections JCF: user defined collections Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 20-1 Developing of a user-defined

More information

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1 Abstract Data Types Add Client Prog Rem Find Data Str. Show 01/22/04 Lecture 4 1 Containers Powerful tool for programming data structures Provides a library of container classes to hold your objects 2

More information

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018 CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node

More information

CMSC132 Summer 2018 Midterm 1. Solution

CMSC132 Summer 2018 Midterm 1. Solution CMSC132 Summer 2018 Midterm 1 Solution First Name (PRINT): Last Name (PRINT): Instructions This exam is a closed-book and closed-notes exam. Total point value is 100 points. The exam is a 80 minutes exam.

More information

In this lecture Simple List Algorithms

In this lecture Simple List Algorithms In this lecture Simple List Algorithms 15-211 Fundamental Data Structures and Algorithms Ananda Guna & Klaus Sutner January 16, 2003 Based on lectures given by Peter Lee, Avrim Blum, Danny Sleator, William

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS 314 Final Fall 2011

CS 314 Final Fall 2011 Points off 1 2A 2B 2C 3 4 5 Total off Net Score CS 314 Final Fall 2011 Your Name_ Your UTEID Instructions: 1. There are 5 questions on this test. 2. You have 3 hours to complete the test. 3. You may not

More information

Lecture 27. Binary Search Trees. Binary Search Trees

Lecture 27. Binary Search Trees. Binary Search Trees Lecture Binary Search Trees Binary Search Trees In the previous lecture, we defined the concept of binary search tree as a binary tree of nodes containing an ordered key with the following additional property.

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

Introduction to Computer Science II CS S-20 Linked Lists III

Introduction to Computer Science II CS S-20 Linked Lists III Introduction to Computer Science II CS112-2012S-20 Linked Lists III David Galles Department of Computer Science University of San Francisco 20-0: Linked List Previous Practical Example: removeat(int index)

More information

CSE 143 Lecture 4. Preconditions

CSE 143 Lecture 4. Preconditions CSE 143 Lecture 4 Exceptions and ArrayList slides created by Marty Stepp http://www.cs.washington.edu/143/ Preconditions precondition: Something your method assumes is true at the start of its execution.

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Stack and queues Array-based implementations

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Exam Name: Email Address: TA: Section: You have three hours to complete this exam. For coding questions, you do not need to include

More information

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

More information

Lecture 8: Iterators and More Mutation

Lecture 8: Iterators and More Mutation 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

More information

January 24, Abstract Data Types (ADTs) An ADT is an abstraction of a data structure.

January 24, Abstract Data Types (ADTs) An ADT is an abstraction of a data structure. Lists CSE 2011 Winter 2007 January 24, 2007 1 Abstract Data Types (ADTs) An ADT is an abstraction of a data structure. An ADT specifies: data stored operations on the data error conditions associated with

More information

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it Design Patterns The Gang of Four suggests a few strategies for creating good o-o designs, including Façade Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it One

More information

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Página 1 de 30 Java TM 2 Platform

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

Software Construction

Software Construction Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering

More information

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock) Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

CS 307 Final Spring 2010

CS 307 Final Spring 2010 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2010 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

More information

package weiss.util; // Fig , pg // Fig 6.16,6.17, pg package weiss.util;

package weiss.util; // Fig , pg // Fig 6.16,6.17, pg package weiss.util; package weiss.util; // Fig 6.9-10, pg 192-4. public interface Collection extends java.io.serializable int size( ); boolean isempty( ); boolean contains( Object x ); boolean add( Object x ); boolean remove(

More information

Inheritance in Java. Steven Zeil. October 25, Class Inheritance Shrubs and Trees Inheriting from Object...

Inheritance in Java. Steven Zeil. October 25, Class Inheritance Shrubs and Trees Inheriting from Object... Steven Zeil October 25, 2013 Contents 1 Class Inheritance 2 1.1 Shrubs and Trees........ 2 1.2 Inheriting from Object..... 3 2 Dynamic Binding in Java 4 2.1 The Animal Example in Java.. 4 2.2 The Key Pattern

More information

JAVA.UTIL.LINKEDLIST CLASS

JAVA.UTIL.LINKEDLIST CLASS JAVA.UTIL.LINKEDLIST CLASS http://www.tutorialspoint.com/java/util/java_util_linkedlist.htm Copyright tutorialspoint.com Introduction The java.util.linkedlist class operations perform we can expect for

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

CMSC 132, Object-Oriented Programming II Summer Lecture 6: CMSC 132, Object-Oriented Programming II Summer 2017 Lecturer: Anwar Mamat Lecture 6: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 6.1 Singly

More information

CS 314 Midterm 2 Spring 2013

CS 314 Midterm 2 Spring 2013 Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Spring 2013 Your Name Your UTEID Circle yours TA s name: Donghyuk Lixun Padmini Zihao Instructions: 1. There are 5 questions on this test. The

More information

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures Abstract Data Types (ADTs) Class #08: Linear Data Structures Software Design III (CS 340): M. Allen, 08 Feb. 16 An ADT defines a kind of computational entity: A set of objects, with possible values A set

More information