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

Similar documents
Data Structures in the Java API

D06 PROGRAMMING with JAVA

Practical Session 4 Java Collections

STACKS,QUEUES, AND LINKED LISTS

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

Data Structures and Algorithms Lists

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

Data Structures and Algorithms

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

DATA STRUCTURE - STACK

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

Universidad Carlos III de Madrid

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

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

CMSC 202H. ArrayList, Multidimensional Arrays

7.1 Our Current Model

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

Lecture 2: Data Structures Steven Skiena. skiena

Algorithms and Data Structures

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

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

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

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

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

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

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

CmpSci 187: Programming with Data Structures Spring 2015

Java Application Developer Certificate Program Competencies

DATA STRUCTURES USING C

Class 32: The Java Collections Framework

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!

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

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

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

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

Chapter 8: Bags and Sets

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

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

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Programming with Data Structures

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

Software Engineering Techniques

Fundamentals of Java Programming

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

Introduction to Data Structures

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

DATA STRUCTURE - QUEUE

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

Structural Design Patterns Used in Data Structures Implementation

Introduction to Stacks

Linked Lists Linked Lists, Queues, and Stacks

Chapter 3: Restricted Structures Page 1

LINKED DATA STRUCTURES

Sequential Data Structures

Stacks. Linear data structures

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

Data Structures and Algorithms V Otávio Braga

Efficient Data Structures for Decision Diagrams

10CS35: Data Structures Using C

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

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

JAVA COLLECTIONS FRAMEWORK

Marist School Computational Media. Processing Exercise 01 Bouncing Ball Animation. Description:

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

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

Analysis of a Search Algorithm

Habanero Extreme Scale Software Research Project

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

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

Glossary of Object Oriented Terms

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

Data Structures. Level 6 C Module Descriptor

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

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

Module 2 Stacks and Queues: Abstract Data Types

Chapter 7: Sequential Data Structures

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

Java Software Structures

Working with Java Collections

Chapter 14 The Binary Search Tree

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

Load balancing Static Load Balancing

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Stacks. Data Structures and Data Types. Collections

Algorithms and Abstract Data Types

The Java Collections Framework

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

CompSci-61B, Data Structures Final Exam

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

C# Cookbook. Stephen Teilhet andjay Hilyard. O'REILLY 8 Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo '"J""'

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

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

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

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

Transcription:

Chapter 20 Lists, Stacks, Queues, and Priority Queues Objectives q To explore the relationship between interfaces and classes in the Java Collections Framework hierarchy ( 20.2). q To use the common methods defined in the Collection interface for operating collections ( 20.2). q To use the Iterator interface to traverse the elements in a collection ( 20.3). q To use a for-each loop to traverse the elements in a collection ( 20.3). q To explore how and when to use ArrayList or LinkedList to store elements ( 20.4). q To compare elements using the Comparable interface and the Comparator interface ( 20.5). q To use the static utility methods in the Collections class for sorting, searching, shuffling lists, and finding the largest and smallest element in collections ( 20.6). q To develop a multiple bouncing balls application using ArrayList ( 20.7). q To distinguish between Vector and ArrayList and to use the Stack class for creating stacks ( 20.8). q To explore the relationships among Collection, Queue, LinkedList, and PriorityQueue and to create priority queues using the PriorityQueue class ( 20.9). q To use stacks to write a program to evaluate expressions ( 20.10). 1 2 What is Data Structure? A data structure is a collection of data organized in some fashion. The structure not only stores data, but also supports operations for accessing and manipulating the data. Java Collection Framework hierarchy A collection is a container object that holds a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named lists, sets, and maps. 3 4

Java Collection Framework hierarchy, cont. Set and List are subinterfaces of Collection. java.util.collection<e> +add(e: E): boolean +addall(c: Collection<? extends E>): boolean +clear(): void +contains(o: Object): boolean +containsall(c: Collection<?>):boolean +isempty(): boolean +remove(o: Object): boolean +removeall(c: Collection<?>): boolean +retainall(c: Collection<?>): boolean +size(): int java.lang.iterable<e> +iterator(): Iterator<E> +foreach(action: Consumer<? super E>): default void +toarray(): Object[] +stream(): Stream default +parallelstream(): Stream default Returns an iterator for the elements in this collection. Performs an action for each element in this iterator. The Collection Interface The Collection interface is for manipulating a collection of objects. Adds a new element e to this collection. Adds all the elements in the collection c to this collection. Removes all the elements from this collection. Returns true if this collection contains the element o. Returns true if this collection contains all the elements in c. Returns true if this collection contains no elements. Removes the element o from this collection. Removes all the elements in c from this collection. Retains the elements that are both in c and in this collection. Returns the number of elements in this collection. Returns an array of Object for the elements in this collection. Returns a stream from this collection (covered in Ch 23). Returns a parallel stream from this collection (covered in Ch 23). java.util.iterator<e> +hasnext(): boolean +next(): E +remove(): void Returns true if this iterator has more elements to traverse. Returns the next element from this iterator. Removes the last element obtained using the next method. 5 6 The List Interface The List Interface, cont. A list stores elements in a sequential order, and allows the user to specify where the element is stored. The user can access the elements by index. 7 8

The List Iterator ArrayList and LinkedList The ArrayList class and the LinkedList class are concrete implementations of the List interface. Which of the two classes you use depends on your specific needs. If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements from any place in the list, you should choose LinkedList. A list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array. 9 10 java.util.arraylist java.util.linkedlist java.util.collection<e> java.util.list<e> java.util.collection<e> java.util.list<e> java.util.linkedlist<e> java.util.arraylist<e> +ArrayList() +ArrayList(c: Collection<? extends E>) +ArrayList(initialCapacity: int) +trimtosize(): void Creates an empty list with the default initial capacity. Creates an array list from an existing collection. Creates an empty list with the specified initial capacity. Trims the capacity of this ArrayList instance to be the list's current size. +LinkedList() +LinkedList(c: Collection<? extends E>) +addfirst(o: E): void +addlast(o: E): void +getfirst(): E +getlast(): E +removefirst(): E +removelast(): E Creates a default empty linked list. Creates a linked list from an existing collection. Adds the object to the head of this list. Adds the object to the tail of this list. Returns the first element from this list. Returns the last element from this list. Returns and removes the first element from this list. Returns and removes the last element from this list. 11 12

Example: Using ArrayList and LinkedList This example creates an array list filled with numbers, and inserts new elements into the specified location in the list. The example also creates a linked list from the array list, inserts and removes the elements from the list. Finally, the example traverses the list forward and backward. The Comparator Interface Sometimes you want to compare the elements of different types. The elements may not be instances of Comparable or are not comparable. You can define a comparator to compare these elements. To do so, define a class that implements the java.util.comparator interface. The Comparator interface has the compare method for comparing two objects. TestArrayAndLinkedList 13 14 The Comparator Interface Other Comparator Examples public int compare(object element1, Object element2) Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal. SortStringByLength SortStringIgnoreCase GeometricObjectComparator TestComparator 15 16

The Collections Class The Collections Class UML Diagram The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating readonly collection classes. 17 18 Case Study: Multiple Bouncing Balls The Vector and Stack Classes javafx.scene.shape.circle m Ball dx: double dy: double +Ball(x: double, y: double, radius: double, color: Color) 1 javafx.scene.layout.pane 1 MultipleBallPane -animation: Timeline +MultipleBallPane() +play(): void +pause(): void +increasespeed(): void +decreasespeed(): void +rateproperty(): DoubleProperty +moveball(): void 1 javafx.application.application -char token +gettoken MultipleBounceBall +settoken +paintcomponet +mouseclicked The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them are the Vector class and the Stack class. These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility. This section introduces the Vector class and the Stack class. MultipleBounceBall 19 20

The Vector Class The Vector Class, cont. In Java 2, Vector is the same as ArrayList, except that Vector contains the synchronized methods for accessing and modifying the vector. None of the new collection data structures introduced so far are synchronized. If synchronization is required, you can use the synchronized versions of the collection classes. These classes are introduced later in the section, The Collections Class. 21 22 java.util.vector<e> java.util.stack<e> +Stack() +empty(): boolean +peek(): E +pop(): E +push(o: E) : E +search(o: Object) : int The Stack Class The Stack class represents a last-in-firstout stack of objects. The elements are accessed only from the top of the stack. Yo u can ret ri ev e, i n s ert, o r remo ve an element from the top of the stack. Creates an empty stack. Returns true if this stack is empty. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns the position of the specified element in this stack. Queues and Priority Queues A queue is a first-in/first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue. In a priority queue, elements are assigned priorities. When accessing elements, the element with the highest priority is removed first. 23 24

The Queue Interface Using LinkedList for Queue 25 26 The PriorityQueue Class Case Study: Evaluating Expressions Stacks can be used to evaluate expressions. PriorityQueueDemo Evaluate Expression 27 28

Algorithm Phase 1: Scanning the expression The program scans the expression from left to right to extract operands, operators, and the parentheses. 1.1. If the extracted item is an operand, push it to operandstack. 1.2. If the extracted item is a + or - operator, process all the operators at the top of operatorstack and push the extracted operator to operatorstack. 1.3. If the extracted item is a * or / operator, process the * or / operators at the top of operatorstack and push the extracted operator to operatorstack. 1.4. If the extracted item is a ( symbol, push it to operatorstack. 1.5. If the extracted item is a ) symbol, repeatedly process the operators from the top of operatorstack until seeing the ( symbol on the stack. Example Phase 2: Clearing the stack Repeatedly process the operators from the top of operatorstack until operatorstack is empty. 29 30