Chapter 3 Introduction to Collections – Stacks Modified

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Advertisements

Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Chapter 12: Data Structures
Chapter 3 Collections. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 3-2 Chapter Objectives Define the concept and terminology related.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
CHAPTER 3 COLLECTIONS SET Collection. 2 Abstract Data Types A data type consists of a set of values or elements, called its domain, and a set of operators.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
1 Data Structures  We can now explore some advanced techniques for organizing and managing information  Chapter 12 of the book focuses on: dynamic structures.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 12 Collections. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Collections A collection is an object that helps us organize and manage.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Lecture 9 Concepts of Programming Languages
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
Chapter 12 Introduction to Collections - Stacks
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Linked Structures - Review Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
Java Software Solutions Lewis and Loftus Chapter 9 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Enhanced Class Design -- Introduction.
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Collections Using Generics in Collections. 2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
COS 312 DAY 18 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA –
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
Click to edit Master text styles Stacks Data Structure.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Next Capstone progress report is April 25 Assignment 5 OVERDUE – Will be graded tomorrow Assignment.
Sections 3.4 Formal Specification
Stack: a Linked Implementation
CHAPTER 4: Linked Structures
12 Collections Software Solutions Lewis & Loftus java 5TH EDITION
Chapter 12: Data Structures
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Chapter 3 Introduction to Collections - Stacks
Chapter 4 Linked Structures - Stacks
Chapter 5 Queues.
Java Software Structures: John Lewis & Joseph Chase
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
Stacks, Queues, and Deques
A type is a collection of values
CHAPTER 3: Collections—Stacks
Presentation transcript:

Chapter 3 Introduction to Collections – Stacks Modified

Chapter Scope Collection terminology The Java 7 Collections API Abstract nature of collections Stacks Conceptually Used to solve problems Implementation using arrays Java Software Structures, 4th Edition, Lewis/Chase

Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing its elements Many standard collections have been defined over time Some collections are linear (has a predecessor and successor) in nature, others are non-linear Java Software Structures, 4th Edition, Lewis/Chase

Linear and Non-Linear Collections Java Software Structures, 4th Edition, Lewis/Chase

Abstraction An abstraction hides details to make a concept easier to manage All (OOPS) objects are abstractions in that they provide well-defined operations (the interface) They hide (encapsulate) the object's data and the implementation of the operations An object (class) is a great mechanism for implementing a collection Java Software Structures, 4th Edition, Lewis/Chase

Abstract Data Type A data type is a group of values and the operations defined on those values An abstract data type (ADT) is a data type that isn't pre-defined in the programming language A data structure is the set of programming constructs and techniques used to implement a collection – i.e. Implementation of a collection ADT The distinction between the terms ADT, data structure, and collection is sometimes blurred in casual use Java Software Structures, 4th Edition, Lewis/Chase

Collection Abstraction A class that uses a collection (client class), interacts with that class through a particular interface (generic sense) = declarations of its public members. Client A Java interface is an abstract class that is used to specify an interface (in the generic sense of the term) that classes can implement. Java Software Structures, 4th Edition, Lewis/Chase

The Java Collections API As you know, the various classes provided with Java (the library) are referred to as the Java API (application programmer interface) The subset of those classes that support collections is called the Java Collections API We will explore particular collections within this API. But we will also explore alternative implementations for such collections. We will reinvent the wheel. Java Software Structures, 4th Edition, Lewis/Chase

Stack - Conceptual View A stack is a linear collection whose elements are added/removed in a last in, first out (LIFO) manner Java Software Structures, 4th Edition, Lewis/Chase

Stack Operations Some collections use particular terms for their operations These are the classic stack operations: Java Software Structures, 4th Edition, Lewis/Chase

Object-Oriented Concepts Encapsulation (classes) Type compatibility rules Interfaces Inheritance Polymorphism Generics Java Software Structures, 4th Edition, Lewis/Chase

Generics Suppose we define a stack that holds Object references, which would allow it to hold any object But then we lose control over which types of elements are added to the stack, and we'd have to cast elements to their proper type when removed A better solution is to define a class that is based on a generic type The type is referred to generically in the class, and the specific type is specified only when an object of that class is created Java Software Structures, 4th Edition, Lewis/Chase

Generics The generic type placeholder is specified in angle brackets in the class header: class Box<T> { // declarations and code that refer to T } Any identifier can be used, but T (for Type) or E (for element) have become standard practice Java Software Structures, 4th Edition, Lewis/Chase

Generics Then, when a Box is needed, it is instantiated with a specific class instead of T: Box<Widget> box1 = new Box<Widget>(); Now, box1 can only hold Widget objects The compiler will issue errors if we try to add a non-Widget to the box And when an object is removed from the box, it is assumed to be a Widget Java Software Structures, 4th Edition, Lewis/Chase

Generics Using the same class, another object can be instantiated: Box<Gadget> box2 = new Box<Gadget>(); The box2 object can only hold Gadget objects Generics provide better type management control at compile-time and simplify the use of collection classes Note: In Java, you cannot Instantiate Generic Types with Primitive Types Java Software Structures, 4th Edition, Lewis/Chase

Stacks in the Java API The java.util.Stack class has been part of the Java collections API since Java 1.0. It implements the classic operations, without any separate interfaces defined As we'll see, there is not a lot of consistency regarding how collections are implemented in the Java API, and we'll explore their relative benefits as appropriate Java Software Structures, 4th Edition, Lewis/Chase

Exceptions When should exceptions be thrown from a collection class? Only when a problem is specific to the concept of the collection (not its implementation or its use) There's no need for the user of a collection to worry about it getting "full," so we'll take care of any such limitations internally But a stack should throw an exception if the user attempts to pop an empty stack Java Software Structures, 4th Edition, Lewis/Chase

3.6 A Stack Interface The Java API version of a stack did not rely on a formal interface However, we will define one for our versions To distinguish them, our collection interface names will have ADT (abstract data type) attached, i.e. StackADT Furthermore, our collection classes and interfaces will be defined as part of a package called jsjf Java Software Structures, 4th Edition, Lewis/Chase

package jsjf; /. Defines the interface to a stack collection package jsjf; /** * Defines the interface to a stack collection. * * @author Lewis and Chase * @version 4.0 */ public interface StackADT<T> { * Adds the specified element to the top of this stack. * @param element element to be pushed onto the stack public void push(T element); * Removes and returns the top element from this stack. * @return the element removed from the stack public T pop(); Java Software Structures, 4th Edition, Lewis/Chase

/. Returns without removing the top element of this stack /** * Returns without removing the top element of this stack. * @return the element on top of the stack */ public T peek(); * Returns true if this stack contains no elements. * @return true if the stack is empty public boolean isEmpty(); * Returns the number of elements in this stack. * @return the number of elements in the stack public int size(); * Returns a string representation of this stack. * @return a string representation of the stack public String toString(); } Java Software Structures, 4th Edition, Lewis/Chase

A Stack Interface A UML diagram Java Software Structures, 4th Edition, Lewis/Chase A UML diagram

Implementing a Stack with an Array Let's now explore our own implementation of a stack, using an array as the underlying structure in which we'll store the stack elements We'll have to take into account the possibility that the array could become full And remember that an array of objects really stores references to those objects Java Software Structures, 4th Edition, Lewis/Chase

Implementing Stacks with an Array An array of object references: Java Software Structures, 4th Edition, Lewis/Chase

Managing Capacity The number of cells in an array is called its capacity It's not possible to change the capacity of an array in Java once it's been created Therefore, to expand the capacity of the stack, we'll create a new (larger) array and copy over the elements This will happen infrequently, and the user of the stack need not worry about it happening Java Software Structures, 4th Edition, Lewis/Chase

Implementing Stacks with an Array By convention, collection class names indicate the underlying structure So ours will be called ArrayStack java.util.Stack is an exception to this convention Our solution will keep the bottom of the stack fixed at index 0 of the array A separate integer called top will indicate where the top of the stack is, as well as how many elements are in the stack currently Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Stack with an Array A stack with elements A, B, C, and D pushed on in that order: Java Software Structures, 4th Edition, Lewis/Chase

Pushing and Popping a Stack After pushing element E: After popping: Java Software Structures, 4th Edition, Lewis/Chase

package jsjf; import jsjf. exceptions. ; import java. util. Arrays; / package jsjf; import jsjf.exceptions.*; import java.util.Arrays; /** * An array implementation of a stack in which the * bottom of the stack is fixed at index 0. * * @author Lewis and Chase * @version 4.0 */ public class ArrayStack<T> implements StackADT<T> { private final static int DEFAULT_CAPACITY = 100; private int top; // index of first free cell private T[] stack; Java Software Structures, 4th Edition, Lewis/Chase

/. Creates an empty stack using default capacity /** * Creates an empty stack using default capacity. */ public ArrayStack() { this(DEFAULT_CAPACITY); } * Creates an empty stack using the specified capacity. * @param initialCapacity the initial size of the array public ArrayStack(int initialCapacity) top = 0; stack = (T[])(new Object[initialCapacity]); Java Software Structures, 4th Edition, Lewis/Chase

Creating an Array of a Generic Type You cannot instantiate an array of a generic type directly Instead, create an array of Object references and cast them to the generic type Java Software Structures, 4th Edition, Lewis/Chase

/. Adds the specified element to the top of this stack, expanding /** * Adds the specified element to the top of this stack, expanding * the capacity of the array if necessary. * @param element generic element to be pushed onto stack */ public void push(T element) { if (size() == stack.length) expandCapacity(); stack[top] = element; top++; } * Creates a new array to store the contents of this stack with * twice the capacity of the old one. private void expandCapacity() stack = Arrays.copyOf(stack, stack.length * 2); Java Software Structures, 4th Edition, Lewis/Chase

/. Removes the element at the top of this stack and returns a /** * Removes the element at the top of this stack and returns a * reference to it. * @return element removed from top of stack * @throws EmptyCollectionException if stack is empty */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack"); top--; T result = stack[top]; stack[top] = null; // Why do this? return result; } Java Software Structures, 4th Edition, Lewis/Chase

/. Returns a reference to the element at the top of this stack /** * Returns a reference to the element at the top of this stack. * The element is not removed from the stack. * @return element on top of stack * @throws EmptyCollectionException if stack is empty */ public T peek() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack"); return stack[top-1]; } Java Software Structures, 4th Edition, Lewis/Chase

Defining an Exception An EmptyCollectionException is thrown when a pop or a peek is attempted and the stack is empty The EmptyCollectionException is defined to extend RuntimeException By passing a string into its constructor, this exception can be used for other collections as well Java Software Structures, 4th Edition, Lewis/Chase

package jsjf. exceptions; / package jsjf.exceptions; /** * Represents the situation in which a collection is empty. * * @author Lewis and Chase * @version 4.0 */ public class EmptyCollectionException extends RuntimeException { * Sets up this exception with an appropriate message. * @param collection the name of the collection public EmptyCollectionException(String collection) super("The " + collection + " is empty."); } Java Software Structures, 4th Edition, Lewis/Chase