Lecture 4. The Java Collections Framework

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

D06 PROGRAMMING with JAVA

JAVA COLLECTIONS FRAMEWORK

Universidad Carlos III de Madrid

Datastrukturer och standardalgoritmer i Java

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Data Structures and Algorithms

Data Structures in the Java API

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

Class 32: The Java Collections Framework

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

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

Data Structures and Algorithms Lists

Structural Design Patterns Used in Data Structures Implementation

Fundamentals of Java Programming

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

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

Lecture 2: Data Structures Steven Skiena. skiena

Sequential Data Structures

Java Software Structures

The Java Collections Framework

Data Structures Using C++ 2E. Chapter 5 Linked Lists

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

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Per imparare a programmare bisogna programmare

Chapter 3: Restricted Structures Page 1

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Chapter 8: Bags and Sets

Java Application Developer Certificate Program Competencies

Introduction to Data Structures

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

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

Glossary of Object Oriented Terms

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

Data Structures and Algorithms

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Linked Lists Linked Lists, Queues, and Stacks

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

Computing Concepts with Java Essentials

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

CMSC 202H. ArrayList, Multidimensional Arrays

Singly linked lists (continued...)

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

STACKS,QUEUES, AND LINKED LISTS

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

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

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

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

Analysis of a Search Algorithm

16 Collection Classes

Circular Linked List. Algorithms and Data Structures

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

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

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

7.1 Our Current Model

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

: provid.ir

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

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

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

Object Oriented Software Design

Java SE 8 Programming

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

The ADT Binary Search Tree

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Computer Programming I

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

DATA STRUCTURE - STACK

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Java EE Web Development Course Program

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Introduction to Stacks

10CS35: Data Structures Using C

Useful Java Collections

CompSci-61B, Data Structures Final Exam

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

COSC 3351 Software Design. Architectural Design (II) Edgar Gabriel. Spring Virtual Machine

LINKED DATA STRUCTURES

Unordered Linked Lists

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

HW3: Programming with stacks

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

El Dorado Union High School District Educational Services

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Abstract Data Types. Chapter 2

7. Object-Oriented Programming

Cpt S 223. School of EECS, WSU

ADT Implementation in Java

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Algorithms and Abstract Data Types

Java Interview Questions and Answers

C++ Programming Language

Specialized Programme on Web Application Development using Open Source Tools

A DESIGN PATTERNS PERSPECTIVE ON DATA STRUCTURES. Virginia Niculescu

ADTs,, Arrays, Linked Lists

Transcription:

Lecture 4. The Java s Framework Chapters 6.3-6.4-1 -

Outline Introduction to the Java s Framework Iterators Interfaces Classes Classes - 2 -

The Java s Framework We will consider the Java s Framework as a good example of how to apply the principles of objectoriented software engineering (see Lecture 1) to the design of classical data structures. - 3 -

The Java s Framework A coupled set of classes and interfaces that implement commonly reusable collection data structures. Designed and developed primarily by Joshua Bloch (currently Chief Java Architect at Google). - 4 -

What is a? An object that groups multiple elements into a single unit. Sometimes called a container. - 5 -

What is a Framework? A unified architecture for representing and manipulating collections. Includes: Interfaces: A hierarchy of ADTs. Implementations Algorithms: The methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. These algorithms are polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. - 6 -

History Apart from the Java s Framework, the bestknown examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy. - 7 -

Benefits Reduces programming effort: By providing useful data structures and algorithms, the s Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. Increases program speed and quality: Provides highperformance, high-quality implementations of useful data structures and algorithms. Allows interoperability among unrelated APIs: APIs can interoperate seamlessly, even though they were written independently. Reduces effort to learn and to use new APIs Reduces effort to design new APIs Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. - 8 -

Where is the Java s Framework? Package java.util. In this lecture we will survey the interfaces, abstract classes and classes for linear data structures provided by the Java s Framework. We will not cover all of the details (e.g., the exceptions that may be thrown). For additional details, please see Javadoc, provided with your java distribution. Comments and code in the specific java.util.*.java files, provided with your java distribution. The s Java tutorial, available at http://docs.oracle.com/ javase/tutorial/collections/index.html Chan et al, The Java Class Libraries, Second Edition - 9 -

Core Interfaces - 10 -

Traversing s in Java There are two ways to traverse collections: using Iterators. with the (enhanced) for-each construct - 11 -

Iterators An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. Suppose collection is an instance of a. Then to print out each element on a separate line: Iterator<E> it = collection.iterator(); while (it.hasnext()) System.out.println(it.next()); Note that next() does two things: 1. Returns the current element (initially the first element) 2. Steps to the next element and makes it the current element. - 12 -

Iterators Iterator interface: public interface Iterator<E> { boolean hasnext(); E next(); void remove(); //optional } hasnext() returns true if the iteration has more elements next() returns the next element in the iteration. throws exception if iterator has already visited all elements. remove() removes the last element that was returned by next. remove may be called only once per call to next otherwise throws an exception. Iterator.remove is the only safe way to modify a collection during iteration - 13 -

Implementing Iterators Could make a copy of the collection. Good: could make copy private no other objects could change it from under you. Bad: construction is O(n). Could use the collection itself (the typical choice). Good: construction, hasnext and next are all O(1). Bad: if another object makes a structural change to the collection, the results are unspecified. - 14 -

The Enhanced For-Each Statement Suppose collection is an instance of a. Then for (Object o : collection) System.out.println(o); prints each element of the collection on a separate line. This code is just shorthand: it compiles to use o.iterator(). - 15 -

The Generality of Iterators Note that iterators are general in that they apply to any collection. Could represent a sequence, set or map. Could be implemented using arrays or linked lists. - 16 -

Iterators A Iterator extends Iterator to treat the collection as a list, allowing access to the integer position (index) of elements forward and backward traversal modification and insertion of elements. Iterator Iterator The current position is viewed as being either Before the first element Between two elements After the last element - 17 -

Iterators Iterators support the following methods: Iterator Iterator add(e): inserts element e at current position (before implicit cursor) hasnext() hasprevious() previous(): returns element before current position and steps backward next(): returns element after current position and steps forward nextindex() previousindex() set(e): replaces the element returned by the most recent next() or previous() call remove(): removes the element returned by the most recent next() or previous() call - 18 -

Java s Framework (Ordered Data Types) Now that we are armed with iterators, we are ready to look at the Java s Framework (for s and s) - 19 -

Levels of ion Recall that Java supports three levels of abstraction: Interface Java expression of an ADT Includes method declarations with arguments of specified types, but with empty bodies Class Implements only a subset of an interface. Cannot be used to instantiate an object. (Concrete) Classes May extend one or more abstract classes Must fully implement any interface it implements Can be used to instantiate objects. - 20 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 21 -

The Iterable Interface Allows an Iterator to be associated with an object. The iterator allows an existing data structure to be stepped through sequentially, using the following methods: hasnext() returns true if the iteration has more elements next() returns the next element in the iteration. throws exception if iterator has already visited all elements. remove() removes the last element that was returned by next. remove may be called only once per call to next otherwise throws an exception. Iterator.remove is the only safe way to modify a collection during iteration - 22 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 23 -

The Interface Allows data to be modeled as a collection of objects. In addition to the Iterator interface, provides interfaces for: Creating the data structure add(e) addall(c) Querying the data structure size() isempty() contains(e) containsall(c) toarray() equals(e) Modifying the data structure remove(e) removeall(c) retainall(c) clear() - 24 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 25 -

The Class Skeletal implementation of the interface. For unmodifiable collection, programmer still needs to implement: iterator (including hasnext and next methods) size For modifiable collection, need to also implement: remove method for iterator add - 26 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 27 -

The Interface Extends the s interface to model the data as an ordered sequence of elements, indexed by a 0-based integer index (position). Provides interface for creation of a Iterator Also adds interfaces for: Creating the data structure add(e) append element e to the list add(i, e) insert element e at index i (and shift the elements at i and above one to the right). Querying the data structure get(i) indexof(e) lastindexof sub(i1, i2) Modifying the data structure set(i) remove(e) remove the first element of the list remove(i) remove the element at index i - 28 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 29 -

The Class Skeletal implementation of the interface. For unmodifiable list, programmer needs to implement methods: get size For modifiable list, need to implement set For variable-size modifiable list, need to implement add remove - 30 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 31 -

The Array Class Random access data store implementation of the interface Uses an array for storage. Supports automatic array-resizing Adds methods trimtosize() ensurecapacity(n) clone() removerange(i1, i2) RangeCheck(i): throws exception if i not in range writeobject(s): writes out list to output stream s readobject(s): reads in list from input stream s - 32 -

End of Lecture Jan 17, 2012-33 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 34 -

Similar to Array. The Vector Class But all methods of Vector are synchronized. Guarantees that at most one thread can execute the method at a time. Other threads are blocked, and must wait until the current thread completes. Vector is a so-called legacy class: no longer necessary for new applications, but still in widespread use in existing code. Synchronization can be achieved with Arrays and other classes of the s framework using synchronized wrappers (we will not cover this). - 35 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 36 -

The Stack Class Represents a last-in, first-out (LIFO) stack of objects. Adds 5 methods: push() pop() peek() empty() search(e): return the 1-based position of where an object is on the stack. - 37 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 38 -

The Sequential Class Skeletal implementation of the interface. Assumes a sequential access data store (e.g., linked list) Programmer needs to implement methods listiterator() size() For unmodifiable list, programmer needs to implement list iterator s methods: hasnext() next() hasprevious() previous() nextindex() previousindex() For modifiable list, need to also implement list iterator s set(e) For variable-size modifiable list, need to implement list iterator s add(e) remove() - 39 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 40 -

The Interface Designed for holding elements prior to processing Typically first-in first-out (FIFO) Defines a head position, which is the next element to be removed. Provides additional insertion, extraction and inspection operations. Extends the interface to provide interfaces for: offer(e): add e to queue (if there is room) poll(): return and remove head of queue (return null if empty) remove(): return and remove head of queue (throw exception if empty) peek(): return head of queue (return null if empty) element(): return head of queue (throw exception if empty) - 41 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 42 -

The Linked Class Implements the and interfaces. Uses a doubly-linked list data structure. Extends the interface with additional methods: getfirst() getlast() removefirst() removelast() addfirst(e) addlast(e) These make it easier to use the Linked class to create stacks, queues and deques (double-ended queues). - 43 -

The Linked Class Linked objects are not synchronized by default. However, the Linked iterator is fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. - 44 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 45 -

The Class Skeletal implementation of the interface. Provides implementations for add(e) remove() element() clear() addall(c) - 46 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 47 -

The Priority Class Based on priority heap Elements are prioritized based either on natural order a comparator, passed to the constructor. Provides an iterator We will study this in detail when we get to heaps! - 48 -

The Java s Framework (Ordered Data Types) Interface Class Class Iterable Priority Sequential Array Vector Stack Linked - 49 -

Summary From this lecture you should understand: The purpose and advantages of the Java s Framework How interfaces, abstract classes and classes are used hierarchically to achieve some of the key goals of object-oriented software engineering. The purpose of iterators, and how to create and use them. How the Java s Framework can be used to develop code using general collections, lists, array lists, stacks and queues. - 50 -

For More Details Javadoc, provided with your java distribution. Comments and code in the specific java.util.*.java files, provided with your java distribution. The s Java tutorial, available at http:// docs.oracle.com/javase/tutorial/collections/index.html Chan et al, The Java Class Libraries, Second Edition - 51 -