Lecture 4. The Java Collections Framework

Similar documents
The Java Collections Framework. Chapters 7.5

EECS 2011 M: Fundamentals of Data Structures

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

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Iterators and Sequences

ITI Introduction to Computing II

Generics. IRS W-9 Form

COMP 250. Lecture 8. stack. Sept. 25, 2017

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

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

An Introduction to Data Structures

Lecture 6 Collections

CS/CE 2336 Computer Science II

Class 26: Linked Lists

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

CH7. LIST AND ITERATOR ADTS

Announcements/Follow-ups

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

Day 6. COMP1006/1406 Summer M. Jason Hinek Carleton University

Notes on access restrictions

JAVA.UTIL.LINKEDLIST CLASS

CH7. LIST AND ITERATOR ADTS

CS 231 Data Structures and Algorithms Fall DDL & Queue Lecture 20 October 22, Prof. Zadia Codabux

What is the Java Collections Framework?

Basic Data Structures 1 / 24

Implementing Lists, Stacks, Queues, and Priority Queues

infix expressions (review)

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Basic Data Structures

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

Abstract Data Types Spring 2018 Exam Prep 5: February 12, 2018

Collections and Iterators. Collections

CSC 321: Data Structures. Fall 2013

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

182 review 1. Course Goals

csci 210: Data Structures Stacks and Queues

CSE 131 Computer Science 1 Module 9a: ADT Representations. Stack and queue ADTs array implementations Buffer ADT and circular lists

Class 32: The Java Collections Framework

Lists. The List ADT. Reading: Textbook Sections

Data Abstraction and Specification of ADTs

Doubly LinkedList is Symmetrical! LinkedList Efficiency. Monday, April 8, 13. insert insert remove remove remove walk

1/22/13. Queue? CS 200 Algorithms and Data Structures. Implementing Queue Comparison implementations. Photo by David Jump 9. Colorado State University

1/22/13. Queue. Create an empty queue Determine whether a queue is empty Add a new item to the queue

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

Data Structures and Algorithms

Active Learning: Streams

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CSC 321: Data Structures. Fall 2012

Outline. iterator review iterator implementation the Java foreach statement testing

Generics Collection Framework

CS S-05 Abstract Data Types and Lists 1

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

CS2113 Lab: Collections 10/29/2018

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Queue? Part 4. Queues. Photo by David Jump. Create an empty queue Items leave a queue from its front.

Collections (Java) Collections Framework

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

CSC212:Data Structure

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

CSCI 136 Data Structures & Advanced Programming. Lecture 13 Fall 2018 Instructors: Bill 2

Data Structures. BSc in Computer Science University of New York, Tirana. Assoc. Prof. Marenglen Biba 1-1

CONTAİNERS COLLECTİONS

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

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

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

CS 221 Review. Mason Vail

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

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

CS Ananda Gunawardena

COMP 250 Winter generic types, doubly linked lists Jan. 28, 2016

Arrays. Array Definition

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

COS 226 Algorithms and Data Structures Fall Midterm

Computer Science II (Spring )

COMP 250. Lecture 6. doubly linked lists. Sept. 20/21, 2017

CS 302 ALGORITHMS AND DATA STRUCTURES

Basic Principles of analysis and testing software

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

9/26/2018 Data Structure & Algorithm. Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps

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

DM550 Introduction to Programming part 2. Jan Baumbach.

CSE 143 SAMPLE MIDTERM

Java Collections Framework: Interfaces

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1

Lists. Outline. COMP9024: Data Structures and Algorithms. Lists. Array List ADT. Array-Based Implementation. Array lists Node lists Iterators

Java Collection Framework

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

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

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

C27a: Stack and Queue

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

9/16/2010 CS Ananda Gunawardena

Stacks and Queues

Transcription:

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 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. - 3 -

Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 4 -

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. - 5 -

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 (former Chief Java Architect at Google). - 6 -

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

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. - 8 -

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 applications: applications can interoperate seamlessly, even though they were written independently. Reduces effort to learn and to use new applications Reduces effort to design new applications Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. - 9 -

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 - 10 -

Core Interfaces - 11 -

Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 12 -

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

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 the collection s 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. - 14 -

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 - 15 -

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. - 16 -

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(). - 17 -

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. - 18 -

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 - 19 -

Iterators Iterators support the following methods: Iterator Iterator add(e): inserts element e at current position 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 - 20 -

Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 21 -

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) Class May extend one or more abstract classes Must fully implement any interface it implements Can be used to instantiate objects. - 22 -

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

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 - 24 -

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

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) to() equals(c) Modifying the data structure remove(e) removeall(c) retainall(c) clear() - 26 -

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

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 - 28 -

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

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 position i (and shift elements at i and above one to the right). Querying the data structure get(i) return element currently stored at position i indexof(e) return index of first occurrence of specified element e lastindexof(e) return index of last occurrence of specified element e sub(i1, i2) return list of elements from index i1 to i2 Modifying the data structure set(i, e) replace element currently stored at index i with specified element e remove(e) remove the first occurrence of the specified element from the list remove(i) remove the element at position i - 30 -

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

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 - 32 -

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

The Class Random access data store implementation of the interface Uses an array for storage. Supports automatic array-resizing Adds methods trimtosize() Trims capacity to current size ensurecapacity(n) Increases capacity to at least n clone() Create copy of list removerange(i1, i2) Remove elements at positions i1 to 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 - 34 -

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

Similar to. The Vector Class But all methods of Vector are synchronized. Uses an internal lock to prevent multiple threads from concurrently executing methods for the same vector object. Other threads trying to execute methods of the object are suspended until the current thread completes. Helps to prevent conflicts and inconsistencies in multi-threaded code 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 s and other classes of the s framework using synchronization wrappers (we will not cover this). - 36 -

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

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. Note: it is now recommended that LIFO functionality be implemented using doubleended queues (java.util.) instead of java.util.stack. Java.util.Stack needlessly exposes positions through search Java.util.stack has no interface, requiring an early commitment to a concrete class. - 38 -

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

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() - 40 -

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

The Interface Designed for holding elements prior to processing. Could be used for first-in first-out (FIFO) or last-in first-out (LIFO) functionality. 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 (return false if not) 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) - 42 -

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

The Interface Supports element insertion and removal at both ends First-in first-out (FIFO) or last-in first-out (LIFO) functionality Methods Equivalent of Equivalent of Stack - 44 -

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

Class Resizable array implementation of the interface. objects are not synchronized by default. However, the iterator is fail-fast: if the deque 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. This is detected at the first execution of one of the iterator s methods after the modification. In this way the iterator will hopefully fail quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. - 46 -

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

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). - 48 -

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. This is detected at the first execution of one of the iterator s methods after the modification. In this way the iterator will hopefully fail quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. - 49 -

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

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

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

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! - 53 -

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

Learning Outcomes 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. - 55 -

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 - 56 -

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