© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using.

Slides:



Advertisements
Similar presentations
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Advertisements

Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Inheritance Inheritance Reserved word protected Reserved word super
CHAPTER 3 COLLECTIONS Abstract Data Types. 2 A data type consists of a set of values or elements, called its domain, and a set of operators acting on.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
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.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Stacks Stack Applications Evaluating Postfix Expressions Introduction to Project 2 Reading: L&C Section 3.2,
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
© 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.
Chapter 2 Object-Oriented Design. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 2-2 Chapter Objectives Review the core concepts underlying.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Appendix B: Object-Oriented Design Java Software Structures: Designing.
Chapter 12 Introduction to Collections - Stacks
Java Software Solutions Foundations of Program Design Sixth Edition
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
Chapter 12 Collections. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Collections A collection is an object that helps us organize and manage.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 12: Multi-way Search Trees Java Software Structures: Designing.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
© 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.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
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.
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.
Stacks Stack Abstract Data Type (ADT) Stack ADT Interface
CHAPTER 4: Linked Structures
12 Collections Software Solutions Lewis & Loftus java 5TH EDITION
Chapter 14: Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Creating Objects & String Class
Java Software Structures: John Lewis & Joseph Chase
Chapter 3 Introduction to Collections - Stacks
Java Software Structures: John Lewis & Joseph Chase
Java Software Structures: John Lewis & Joseph Chase
CSC 1052 Stacks 1/11/2019.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
A type is a collection of values
CHAPTER 3: Collections—Stacks
Presentation transcript:

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using Data Structures Third Edition John Lewis & Joseph Chase

1-2 © 2010 Pearson Addison-Wesley. All rights reserved. 1-2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure of the Java Collections API Discuss the abstract design of collections Define a set collection Use a set collection to solve a problem Examine an array implementation of a set

1-3 © 2010 Pearson Addison-Wesley. All rights reserved. 1-3 Collections A collection is an object that gathers and organizes other objects (elements) Many types of fundamental collections have been defined: stack, queue, list, tree, graph, etc. They can be broadly categorized as linear (organizes the elements in a straight line) or nonlinear

1-4 © 2010 Pearson Addison-Wesley. All rights reserved. 1-4 A linear and a nonlinear collection

1-5 © 2010 Pearson Addison-Wesley. All rights reserved. 1-5 Collections The elements within a collection are usually organized based on: –the order in which they were added to a collection, or –some inherent relationship among the elements themselves For example, a list of people may be kept in alphabetical order by name or in the order in which they were added to the list Which type of collection you use depends on what you are trying to accomplish

1-6 © 2010 Pearson Addison-Wesley. All rights reserved. 1-6 Abstraction An abstraction hides certain details at certain times It provides a way to deal with the complexity of a large system A collection, like any well-defined object, is an abstraction We want to separate the interface of the collection (how we interact with it) from the underlying details of how we choose to implement it

1-7 © 2010 Pearson Addison-Wesley. All rights reserved. 1-7 A well-defined interface masks the implementation of the collection.

1-8 © 2010 Pearson Addison-Wesley. All rights reserved. 1-8 Issues with Collections For each collection we examine, we will consider: –How does the collection operate conceptually? –How do we formally define its interface? –What kinds of problems does it help us solve? –What ways might we implement it? –What are the benefits and costs of each implementation?

1-9 © 2010 Pearson Addison-Wesley. All rights reserved. 1-9 Terms The terms used in the study of collections are defined in a variety of ways Our definitions: –data type – a group of values and the operations defined on those values –abstract data type – a data type whose values and operations are not inherently defined in a programming language –data structure – the programming constructs used to implement a collection

1-10 © 2010 Pearson Addison-Wesley. All rights reserved The Java Collections API The Java Collections API is a set of classes that represent some specific collection types, implemented in various ways It is part of the large class library that can be used by any Java program API stands for Application Programming Interface As we explore various collections, we will examine the appropriate classes in the Java Collections API

1-11 © 2010 Pearson Addison-Wesley. All rights reserved A Stack Collection Let's look at an example of a collection A stack collection arranges elements in a last in, first out manner (LIFO) It is very similar to a stack of plates, books, etc. You may only place new elements on the top of the stack You may only remove elements from the top of the stack

1-12 © 2010 Pearson Addison-Wesley. All rights reserved The conceptual view of a stack collection

1-13 © 2010 Pearson Addison-Wesley. All rights reserved Collection Operations Every collection has a set of operations that define how we interact with it They usually include ways for the user to: –add and remove elements –determine if the collection is empty –determine the collection's size

1-14 © 2010 Pearson Addison-Wesley. All rights reserved The operations on a stack collection

1-15 © 2010 Pearson Addison-Wesley. All rights reserved What do we store? So what do we store in our stack collection? Could recreate our stack each time with a specific type – Very Inefficient! Instead, create collection once and reuse Must maintain type compatibility and type checking Let’s explore some possibilities using inheritance and polymorphism

1-16 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance In object-oriented programming, inheritance means to derive a class from the definition of another class In general, creating a new class via inheritance is faster, easier, and cheaper Inheritance is at the heart of software reuse

1-17 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance The word class comes from the idea of classifying groups of objects with similar characteristics For example, all mammals share certain characteristics: –Warm blooded –Have hair –Bear live offspring

1-18 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance In software, a mammal class would have variables and methods that describe the state and behavior of mammals From that class, we could derive a horse class The horse class would inherit all of the variables and methods of the mammal class The horse class could also define additional variables and methods of its own

1-19 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance The original class that is used to derive a new one is called the parent class, superclass, or base class The derivation process establishes an is-a relationship between the two classes For example, a horse is-a mammal

1-20 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance - Class Hierarchies A child class derived from one parent can be the parent of its own child class Multiple child classes may also be derived from a single parent Thus inheritance relationships often develop into class hierarchies

1-21 © 2010 Pearson Addison-Wesley. All rights reserved A UML class diagram showing a class hierarchy

1-22 © 2010 Pearson Addison-Wesley. All rights reserved Inheritance - the Object Class In Java, all classes are derived ultimately from the Object class The Object class provides a toString method which is often overridden The Object class provides an equals method that tests to see if two objects are aliases and is also often overridden

1-23 © 2010 Pearson Addison-Wesley. All rights reserved Polymorphism The term polymorphism can be defined as “having many forms” A polymorphic reference is a reference variable that can refer to different types of objects at different points in time The specific method invoked by a polymorphic reference can change from one invocation to the next

1-24 © 2010 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism results in the need for dynamic binding Usually binding of a call to the code occurs at compile time Dynamic binding means that this binding cannot occur until run time

1-25 © 2010 Pearson Addison-Wesley. All rights reserved Polymorphism In Java, a reference that is declared to refer to an object of a particular class can also be used to refer to an object of any class related to it by inheritance For example: Mammal pet; Horse secretariat = new Horse(); pet = secretariat; // a valid assignment This is polymorphism as a result of inheritance

1-26 © 2010 Pearson Addison-Wesley. All rights reserved Polymorphism to the extreme Using polymorphism via inheritance, a reference of type Object can refer to any object of any type Thus we could store Object references in our stack allowing us to store objects of any type This creates some interesting problems: Animal[ ] creatures = new Mammal[10]; creatures[1] = new Reptile(); should not work but it does compile!

1-27 © 2010 Pearson Addison-Wesley. All rights reserved Generic Types Using the Object class does not provide us a type-safe solution for our collection Java enables us to define a class based upon a generic type This means that we can define a class so that it stores, operates on, and manages objects whose type is not specified until the class is instantiated

1-28 © 2010 Pearson Addison-Wesley. All rights reserved Generic Types Assume that we need to define a class named Box that stores and manages other objects class Box { // declarations and code that manage // objects of type T }

1-29 © 2010 Pearson Addison-Wesley. All rights reserved Generic Types Then if we wanted to instantiate a Box to hold objects of the Widget class Box box1 = new Box (); But we could also instantiate a Box to hold objects of the Gadget class Box box2 = new Box ();

1-30 © 2010 Pearson Addison-Wesley. All rights reserved Generic Types The type supplied at the time of instantiation replaces the type T wherever it is used in the declaration of the class A generic type such as T cannot be instantiated We will use generics throughout the book to develop collection classes

1-31 © 2010 Pearson Addison-Wesley. All rights reserved Java Interfaces The programming construct in Java called an interface is a convenient way to define the operations on a collection A Java interface lists the set of abstract methods (no bodies) that a class implements It provides a way to establish a formal declaration that a class will respond to a particular set of messages (method calls)

1-32 © 2010 Pearson Addison-Wesley. All rights reserved The StackADT interface /** Lewis and Chase * * Defines the interface to a stack data structure. */ package jss2; public interface StackADT { /** Adds one element to the top of this stack. element element to be pushed onto stack */ public void push (T element); /** Removes and returns the top element from this stack. T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. T element on top of the stack */ public T peek(); /** Lewis and Chase * * Defines the interface to a stack data structure. */ package jss2; public interface StackADT { /** Adds one element to the top of this stack. element element to be pushed onto stack */ public void push (T element); /** Removes and returns the top element from this stack. T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. T element on top of the stack */ public T peek();

1-33 © 2010 Pearson Addison-Wesley. All rights reserved The StackADT interface (continued) /** Returns true if this stack contains no elements. boolean whether or not this stack is empty */ public boolean isEmpty(); /** Returns the number of elements in this stack. int number of elements in this stack */ public int size(); /** Returns a string representation of this stack. String representation of this stack */ public String toString(); } /** Returns true if this stack contains no elements. boolean whether or not this stack is empty */ public boolean isEmpty(); /** Returns the number of elements in this stack. int number of elements in this stack */ public int size(); /** Returns a string representation of this stack. String representation of this stack */ public String toString(); }

1-34 © 2010 Pearson Addison-Wesley. All rights reserved UML description of the SetADT interface

1-35 © 2010 Pearson Addison-Wesley. All rights reserved Using Stacks Stacks are particularly helpful when solving certain types of problems Consider the undo operation in an application –keeps track of the most recent operations in reverse order

1-36 © 2010 Pearson Addison-Wesley. All rights reserved Postfix Expressions Let's examine a program that uses a stack to evaluate postfix expressions In a postfix expression, the operator comes after its two operands We generally use infix notation, with parentheses to force precedence: (3 + 4) * 2 In postfix notation, this would be written *

1-37 © 2010 Pearson Addison-Wesley. All rights reserved Postfix Expressions To evaluate a postfix expression: –scan from left to right, determining if the next token is an operator or operand –if it is an operand, push it on the stack –if it is an operator, pop the stack twice to get the two operands, perform the operation, and push the result onto the stack At the end, there will be one value on the stack, which is the value of the expression

1-38 © 2010 Pearson Addison-Wesley. All rights reserved Using a stack to evaluate a postfix expression

1-39 © 2010 Pearson Addison-Wesley. All rights reserved Postfix Expressions To simplify the example, let's assume the operands to the expressions are integer literals Our solution uses a LinkedStack, though any implementation of a stack would suffice

1-40 © 2010 Pearson Addison-Wesley. All rights reserved The Postfix class /** Lewis and Chase * * Demonstrates the use of a stack to evaluate postfix expressions. */ import java.util.Scanner; public class Postfix { /** * Reads and evaluates multiple postfix expressions. */ public static void main (String[] args) { String expression, again; int result; try { Scanner in = new Scanner(System.in); /** Lewis and Chase * * Demonstrates the use of a stack to evaluate postfix expressions. */ import java.util.Scanner; public class Postfix { /** * Reads and evaluates multiple postfix expressions. */ public static void main (String[] args) { String expression, again; int result; try { Scanner in = new Scanner(System.in);

1-41 © 2010 Pearson Addison-Wesley. All rights reserved The Postfix class (continued) do { PostfixEvaluator evaluator = new PostfixEvaluator(); System.out.println ("Enter a valid postfix expression: "); expression = in.nextLine(); result = evaluator.evaluate (expression); System.out.println(); System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? "); again = in.nextLine(); System.out.println(); } while (again.equalsIgnoreCase("y")); } catch (Exception IOException) { System.out.println("Input exception reported"); } do { PostfixEvaluator evaluator = new PostfixEvaluator(); System.out.println ("Enter a valid postfix expression: "); expression = in.nextLine(); result = evaluator.evaluate (expression); System.out.println(); System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? "); again = in.nextLine(); System.out.println(); } while (again.equalsIgnoreCase("y")); } catch (Exception IOException) { System.out.println("Input exception reported"); }

1-42 © 2010 Pearson Addison-Wesley. All rights reserved The PostfixEvaluator class /** Lewis and Chase * * Represents an integer evaluator of postfix expressions. Assumes * the operands are constants. */ import jss2.ArrayStack; import java.util.StringTokenizer; public class PostfixEvaluator { /** constant for addition symbol */ private final char ADD = '+'; /** constant for subtraction symbol */ private final char SUBTRACT = '-'; /** constant for multiplication symbol */ private final char MULTIPLY = '*'; /** constant for division symbol */ private final char DIVIDE = '/'; /** the stack */ private ArrayStack stack; /** Lewis and Chase * * Represents an integer evaluator of postfix expressions. Assumes * the operands are constants. */ import jss2.ArrayStack; import java.util.StringTokenizer; public class PostfixEvaluator { /** constant for addition symbol */ private final char ADD = '+'; /** constant for subtraction symbol */ private final char SUBTRACT = '-'; /** constant for multiplication symbol */ private final char MULTIPLY = '*'; /** constant for division symbol */ private final char DIVIDE = '/'; /** the stack */ private ArrayStack stack;

1-43 © 2010 Pearson Addison-Wesley. All rights reserved The PostfixEvaluator class (continued) /** * Sets up this evalutor by creating a new stack. */ public PostfixEvaluator() { stack = new ArrayStack (); } /** * Evaluates the specified postfix expression. If an operand is * encountered, it is pushed onto the stack. If an operator is * encountered, two operands are popped, the operation is * evaluated, and the result is pushed onto the stack. expr String representation of a postfix expression int value of the given expression */ public int evaluate (String expr) { int op1, op2, result = 0; String token; StringTokenizer tokenizer = new StringTokenizer (expr); /** * Sets up this evalutor by creating a new stack. */ public PostfixEvaluator() { stack = new ArrayStack (); } /** * Evaluates the specified postfix expression. If an operand is * encountered, it is pushed onto the stack. If an operator is * encountered, two operands are popped, the operation is * evaluated, and the result is pushed onto the stack. expr String representation of a postfix expression int value of the given expression */ public int evaluate (String expr) { int op1, op2, result = 0; String token; StringTokenizer tokenizer = new StringTokenizer (expr);

1-44 © 2010 Pearson Addison-Wesley. All rights reserved The PostfixEvaluator class (continued) while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (isOperator(token)) { op2 = (stack.pop()).intValue(); op1 = (stack.pop()).intValue(); result = evalSingleOp (token.charAt(0), op1, op2); stack.push (new Integer(result)); } else stack.push (new Integer(Integer.parseInt(token))); } return result; } while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (isOperator(token)) { op2 = (stack.pop()).intValue(); op1 = (stack.pop()).intValue(); result = evalSingleOp (token.charAt(0), op1, op2); stack.push (new Integer(result)); } else stack.push (new Integer(Integer.parseInt(token))); } return result; }

1-45 © 2010 Pearson Addison-Wesley. All rights reserved The PostfixEvaluator class (continued) /** * Determines if the specified token is an operator. token String representing a single token boolean true if token is operator */ private boolean isOperator (String token) { return ( token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") ); } /** * Peforms integer evaluation on a single expression consisting of * the specified operator and operands. operation operation to be performed op1 the first operand op2 the second operand int value of the expression */ private int evalSingleOp (char operation, int op1, int op2) { int result = 0; /** * Determines if the specified token is an operator. token String representing a single token boolean true if token is operator */ private boolean isOperator (String token) { return ( token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") ); } /** * Peforms integer evaluation on a single expression consisting of * the specified operator and operands. operation operation to be performed op1 the first operand op2 the second operand int value of the expression */ private int evalSingleOp (char operation, int op1, int op2) { int result = 0;

1-46 © 2010 Pearson Addison-Wesley. All rights reserved The PostfixEvaluator class (continued) switch (operation) { case ADD: result = op1 + op2; break; case SUBTRACT: result = op1 - op2; break; case MULTIPLY: result = op1 * op2; break; case DIVIDE: result = op1 / op2; } return result; } switch (operation) { case ADD: result = op1 + op2; break; case SUBTRACT: result = op1 - op2; break; case MULTIPLY: result = op1 * op2; break; case DIVIDE: result = op1 / op2; } return result; }

1-47 © 2010 Pearson Addison-Wesley. All rights reserved A UML class diagram for the postfix expression program

1-48 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions Collections must always manage problem situations carefully For example: attempting to remove an element from an empty stack The designer of the collection determines how it might be handled Our implementation provides an isEmpty method, so the user can check beforehand And it throws an exception if the situation arises, which the user can catch

1-49 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions Our stack can be empty, can it ever be full? Intuitively, the underlying data structure (array, linked structure, etc.) could run out of memory The conceptual stack collection cannot be full Thus managing capacity is an issue for our stack implementation

1-50 © 2010 Pearson Addison-Wesley. All rights reserved Managing Capacity An array has a particular number of cells when it is created – its capacity So the array's capacity is also the stack’s capacity What do we do when the stack is full and a new element is added? –We could throw an exception –We could return some kind of status indicator –We could automatically expand the capacity

1-51 © 2010 Pearson Addison-Wesley. All rights reserved Managing Capacity The first two options require the user of the collection to be on guard and deal with the situation as needed The third option is best, especially in light of our desire to separate the implementation from the interface The capacity is an implementation problem, and shouldn't be passed along to the user unless there is a good reason to do so

1-52 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions Problems that arise in a Java program may generate exceptions or errors An exception is an object that defines an unusual or erroneous situation An error is similar to an exception, except that an error generally represents an unrecoverable situation

1-53 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions A program can be designed to process an exception in one of three ways: –Not handle the exception at all –Handle the exception where it occurs –Handle the exception at another point in the program

1-54 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions If an exception is not handled at all by the program, the program will produce an exception message and terminate For example: Exception in three “main” java.lang.ArithmeticException: / by zero at Zero.main (Zero.java:17) This message provides the name of the exception, description of the exception, the class and method, as well as the filename and line number where the exception occurred

1-55 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions To handle an exception when it is thrown, we use a try statement A try statement consists of a try block followed by one or more catch clauses try { // statements in the try block } catch (IOException exception) { // statements that handle the I/O problem }

1-56 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions When a try statement is executed, the statements in the try block are executed If no exception is thrown, processing continues with the statement following the try statement If an exception is thrown, control is immediately passed to the first catch clause whose specified exception corresponds to the class of the exception that was thrown If an exception is not caught and handled where it occurs, control is immediately returned to the method that invoked the method that produced the exception

1-57 © 2010 Pearson Addison-Wesley. All rights reserved Exceptions If that method does not handle the exception (via a try statement with an appropriate catch clause) then control returns to the method that called it This process is called propagating the exception Exception propagation continues until the exception is caught and handled or until it is propagated out of the main method resulting in the termination of the program

1-58 © 2010 Pearson Addison-Wesley. All rights reserved The ArrayStack Class Now let's examine an array-based implementation of a stack We'll make the following design decisions: –maintain an array of generic references –the bottom of the stack is at index 0 –the elements of the stack are in order and contiguous –an integer variable top stores the index of the next available slot in the array This approach allows the stack to grow and shrink at the higher indexes

1-59 © 2010 Pearson Addison-Wesley. All rights reserved An array implementation of a stack

1-60 © 2010 Pearson Addison-Wesley. All rights reserved ArrayStack /** Lewis and Chase * * Represents an array implementation of a stack. */ package jss2; import jss2.exceptions.*; public class ArrayStack implements StackADT { /** * constant to represent the default capacity of the array */ private final int DEFAULT_CAPACITY = 100; /** * int that represents both the number of elements and the next * available position in the array */ private int top; /** * array of generic elements to represent the stack */ private T[] stack; /** Lewis and Chase * * Represents an array implementation of a stack. */ package jss2; import jss2.exceptions.*; public class ArrayStack implements StackADT { /** * constant to represent the default capacity of the array */ private final int DEFAULT_CAPACITY = 100; /** * int that represents both the number of elements and the next * available position in the array */ private int top; /** * array of generic elements to represent the stack */ private T[] stack;

1-61 © 2010 Pearson Addison-Wesley. All rights reserved ArrayStack (continued) /** * Creates an empty stack using the default capacity. */ public ArrayStack() { top = 0; stack = (T[])(new Object[DEFAULT_CAPACITY]); } /** * Creates an empty stack using the specified capacity. initialCapacity represents the specified capacity */ public ArrayStack (int initialCapacity) { top = 0; stack = (T[])(new Object[initialCapacity]); } /** * Creates an empty stack using the default capacity. */ public ArrayStack() { top = 0; stack = (T[])(new Object[DEFAULT_CAPACITY]); } /** * Creates an empty stack using the specified capacity. initialCapacity represents the specified capacity */ public ArrayStack (int initialCapacity) { top = 0; stack = (T[])(new Object[initialCapacity]); }

1-62 © 2010 Pearson Addison-Wesley. All rights reserved ArrayStack – the push operation /** * Adds the specified element to the top of this stack, expanding * the capacity of the stack array if necessary. element generic element to be pushed onto stack */ public void push (T element) { if (size() == stack.length) expandCapacity(); stack[top] = element; top++; } /** * Adds the specified element to the top of this stack, expanding * the capacity of the stack array if necessary. element generic element to be pushed onto stack */ public void push (T element) { if (size() == stack.length) expandCapacity(); stack[top] = element; top++; }

1-63 © 2010 Pearson Addison-Wesley. All rights reserved The stack after pushing element E

1-64 © 2010 Pearson Addison-Wesley. All rights reserved ArrayStack – the pop operation /** * Removes the element at the top of this stack and returns a * reference to it. Throws an EmptyCollectionException if the stack * is empty. T element removed from top of stack EmptyCollectionException if a pop is attempted on empty stack */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); top--; T result = stack[top]; stack[top] = null; return result; } /** * Removes the element at the top of this stack and returns a * reference to it. Throws an EmptyCollectionException if the stack * is empty. T element removed from top of stack EmptyCollectionException if a pop is attempted on empty stack */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); top--; T result = stack[top]; stack[top] = null; return result; }

1-65 © 2010 Pearson Addison-Wesley. All rights reserved The stack after popping the top element

1-66 © 2010 Pearson Addison-Wesley. All rights reserved ArrayStack – the peek operation /** * Returns a reference to the element at the top of this stack. * The element is not removed from the stack. Throws an * EmptyCollectionException if the stack is empty. T element on top of stack EmptyCollectionException if a peek is attempted on empty stack */ public T peek() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); return stack[top-1]; } /** * Returns a reference to the element at the top of this stack. * The element is not removed from the stack. Throws an * EmptyCollectionException if the stack is empty. T element on top of stack EmptyCollectionException if a peek is attempted on empty stack */ public T peek() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); return stack[top-1]; }

1-67 © 2010 Pearson Addison-Wesley. All rights reserved Other operations The size operation is imply a matter of returning the count The isEmpty operation returns true if the count is 0 and false otherwise The toString operation concatenates a string made up of the results of the toString operations for each element in the stack

1-68 © 2010 Pearson Addison-Wesley. All rights reserved Analysis of Stack Operations Because stack operations all work on one end of the collection, they are generally efficient The push and pop operations, for the array implementation are O(1) Likewise, the other operations are also O(1)