SlideShare a Scribd company logo
Implement the ADT stack by using an array stack to contain its entries. Expand the array
dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1].
Your Stack class must implement StackInterface (provided). You may use ArrayStack.java
(provided) as the starting point for your implementation.
You must implement a comprehensive set of unit tests using the main() method (and private
utility methods) in ArrayStack.java.
ArrayStack.java
public class ArrayStack implements StackInterface
{
private T[] stack; // Array of stack entries
private int topIndex; // Index of top entry
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
} // end constructor
// < Implementations of the stack operations go here. >
// < Implementations of the private methods go here; checkCapacity and
// checkInitialization are analogous to those in Chapter 2. >
// . . .
} // end ArrayStack
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry);
/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop();
/** Retrieves this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek();
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
} // end StackInterface
Solution
StackTester.java
public class StackTester
{
public static void main(String[] args)
{
ArrayStack aS = new ArrayStack();
aS.push(3);
aS.push(5);
aS.push(10);
aS.push(11);
System.out.println(""+ aS.peek() + ", " + aS.pop() + ", " + aS.peek2());
aS.remove(1);
}
}
ArrayStack.java
import java.util.Arrays;
public class ArrayStack implements StackInterface
{
private T[] stack;
private int topIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
}
public boolean isEmpty()
{
return topIndex < 0;
}
private void ensureCapacity()
{
if(topIndex == stack.length - 1)
{
int newLength = 2*stack.length;
checkCapacity(newLength);
stack = Arrays.copyOf(stack, newLength);
}
}
private void ensureCapacity(int n)
{
// add n slots to the array
if(topIndex == stack.length - 1){
int newLength = 2*stack.length + n;
checkCapacity(newLength);
stack = Arrays.copyOf(stack, newLength);
}
}
private boolean checkCapacity(int capacity)
{
boolean bool = true;
if(capacity > MAX_CAPACITY)
bool = false;
return bool;
}
private boolean checkInitialized()
{
return initialized;
}
public void push(T newEntry)
{
checkInitialized();
ensureCapacity();
stack[topIndex+1] = newEntry;
topIndex++;
}
public T pop()
{
checkInitialized();
if(!isEmpty())
{
T top = stack[topIndex];
stack[topIndex]= null;
topIndex --;
return top;
} else
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
}
}
public T peek()
{
checkInitialized();
if(isEmpty())
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
} else
return stack[topIndex];
}
public void clear()
{
stack = (T[]) new Object[DEFAULT_CAPACITY];
topIndex = -1;
}
public T peek2()
{
checkInitialized();
if(isEmpty())
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
} else
return stack[topIndex-1];
}
public String toString()
{
String s = "";
for(int i = 0; i < stack.length; i++)
{
s += stack[i] + ",";
}
return s;
}
public void remove(int n)
{
checkInitialized();
if(n <= topIndex)
{
for(int i = n; i < (topIndex - 1); i++)
{
stack[i] = stack[i+1];
}
}
}
public void pushAll(T[] a)
{
checkInitialized();
checkCapacity(topIndex + a.length);
ensureCapacity(a.length);
for(int i = 0; i < a.length; i ++)
{
stack[topIndex + 1] = a[i];
topIndex ++;
}
}
}
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack. */
public void push(T newEntry);
/** Removes and returns this stack's top entry.*/
public T pop();
/** Retrieves this stack's top entry. */
public T peek();
/** Detects whether this stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
public T peek2(); // Returns the element below the top element, or throw an exception if there
are less than two elements
public String toString(); // Returns a string that shows all of the elements on the stack. You can
choose the format.
public void remove(int n); // removes the top n entries from the stack. Stops as soon as the
stack is empty.
public void pushAll(T[] a); // pushes each element in the array , beginning with index 0.
}
Ad

Recommended

Need help with writing the test cases for the following code in java-.docx
Need help with writing the test cases for the following code in java-.docx
LucasmHKChapmant
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
Chandrapriya Jayabal
 
Educational slides by venay magen
Educational slides by venay magen
venaymagen19
 
Stack Implementation
Stack Implementation
Zidny Nafan
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
Please implement Stack using Array (capacity 100)- Use template to.pdf
Please implement Stack using Array (capacity 100)- Use template to.pdf
fashionscollect
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdf
JUSTSTYLISH3B2MOHALI
 
Stacks
Stacks
sardorbek mamazhanov
 
Stacks
Stacks
Temperory mukesh
 
Ch06_Stack_Implementations in data structures.pptx
Ch06_Stack_Implementations in data structures.pptx
rexwilde3095
 
Data Structure - Stack.pptx
Data Structure - Stack.pptx
MarlonMagtibay2
 
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Lalkamal2
 
Stack, queue and hashing
Stack, queue and hashing
Dumindu Pahalawatta
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
vtunali
 
Lec2
Lec2
Nikhil Chilwant
 
1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf
saradashata
 
stacks2
stacks2
Mohamed Elsayed
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
fathimafancyjeweller
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
partho5958
 
Lec2
Lec2
Anjneya Varshney
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
IT2070 Lecture 01 2021.pptx
IT2070 Lecture 01 2021.pptx
DilanAkash1
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
An Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Consider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdf
SIGMATAX1
 
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
SIGMATAX1
 

More Related Content

Similar to Implement the ADT stack by using an array stack to contain its entri.pdf (20)

Stacks
Stacks
sardorbek mamazhanov
 
Stacks
Stacks
Temperory mukesh
 
Ch06_Stack_Implementations in data structures.pptx
Ch06_Stack_Implementations in data structures.pptx
rexwilde3095
 
Data Structure - Stack.pptx
Data Structure - Stack.pptx
MarlonMagtibay2
 
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Lalkamal2
 
Stack, queue and hashing
Stack, queue and hashing
Dumindu Pahalawatta
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
vtunali
 
Lec2
Lec2
Nikhil Chilwant
 
1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf
saradashata
 
stacks2
stacks2
Mohamed Elsayed
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
fathimafancyjeweller
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
partho5958
 
Lec2
Lec2
Anjneya Varshney
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
IT2070 Lecture 01 2021.pptx
IT2070 Lecture 01 2021.pptx
DilanAkash1
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
An Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Ch06_Stack_Implementations in data structures.pptx
Ch06_Stack_Implementations in data structures.pptx
rexwilde3095
 
Data Structure - Stack.pptx
Data Structure - Stack.pptx
MarlonMagtibay2
 
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Lalkamal2
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
vtunali
 
1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf
saradashata
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
fathimafancyjeweller
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
ch14ILFVJHCHFCXCJHBKVJGCHGCHGXZDFUHJU.ppt
partho5958
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
IT2070 Lecture 01 2021.pptx
IT2070 Lecture 01 2021.pptx
DilanAkash1
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
An Introduction to Stack Data Structures
An Introduction to Stack Data Structures
berggold2024
 
introduction stacks in data structures and algorithms
introduction stacks in data structures and algorithms
sneham64878
 
01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 

More from SIGMATAX1 (20)

Consider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdf
SIGMATAX1
 
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
SIGMATAX1
 
Comparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdf
SIGMATAX1
 
Why does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdf
SIGMATAX1
 
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
SIGMATAX1
 
Which of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdf
SIGMATAX1
 
Which of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdf
SIGMATAX1
 
Which of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdf
SIGMATAX1
 
What are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdf
SIGMATAX1
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
SIGMATAX1
 
What is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdf
SIGMATAX1
 
What step of protein synthesis is shown in the figure elongation st.pdf
What step of protein synthesis is shown in the figure elongation st.pdf
SIGMATAX1
 
Water is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdf
SIGMATAX1
 
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
SIGMATAX1
 
The three types of mixtures are and The weak bond forming a bridge .pdf
The three types of mixtures are and The weak bond forming a bridge .pdf
SIGMATAX1
 
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
SIGMATAX1
 
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
SIGMATAX1
 
Required 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdf
SIGMATAX1
 
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
SIGMATAX1
 
Proponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdf
SIGMATAX1
 
Consider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdf
SIGMATAX1
 
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
SIGMATAX1
 
Comparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdf
SIGMATAX1
 
Why does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdf
SIGMATAX1
 
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
SIGMATAX1
 
Which of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdf
SIGMATAX1
 
Which of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdf
SIGMATAX1
 
Which of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdf
SIGMATAX1
 
What are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdf
SIGMATAX1
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
SIGMATAX1
 
What is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdf
SIGMATAX1
 
What step of protein synthesis is shown in the figure elongation st.pdf
What step of protein synthesis is shown in the figure elongation st.pdf
SIGMATAX1
 
Water is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdf
SIGMATAX1
 
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
SIGMATAX1
 
The three types of mixtures are and The weak bond forming a bridge .pdf
The three types of mixtures are and The weak bond forming a bridge .pdf
SIGMATAX1
 
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
SIGMATAX1
 
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
SIGMATAX1
 
Required 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdf
SIGMATAX1
 
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
SIGMATAX1
 
Proponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdf
SIGMATAX1
 
Ad

Recently uploaded (20)

VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
RAKESH SAJJAN
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
Communicable Diseases and National Health Programs – Unit 9 | B.Sc Nursing 5t...
RAKESH SAJJAN
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
Ad

Implement the ADT stack by using an array stack to contain its entri.pdf

  • 1. Implement the ADT stack by using an array stack to contain its entries. Expand the array dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1]. Your Stack class must implement StackInterface (provided). You may use ArrayStack.java (provided) as the starting point for your implementation. You must implement a comprehensive set of unit tests using the main() method (and private utility methods) in ArrayStack.java. ArrayStack.java public class ArrayStack implements StackInterface { private T[] stack; // Array of stack entries private int topIndex; // Index of top entry private boolean initialized = false; private static final int DEFAULT_CAPACITY = 50; private static final int MAX_CAPACITY = 10000; public ArrayStack() { this(DEFAULT_CAPACITY); } // end default constructor public ArrayStack(int initialCapacity) { checkCapacity(initialCapacity); // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; stack = tempStack; topIndex = -1; initialized = true; } // end constructor // < Implementations of the stack operations go here. > // < Implementations of the private methods go here; checkCapacity and // checkInitialization are analogous to those in Chapter 2. >
  • 2. // . . . } // end ArrayStack StackInterface.java public interface StackInterface { /** Adds a new entry to the top of this stack. @param newEntry An object to be added to the stack. */ public void push(T newEntry); /** Removes and returns this stack's top entry. @return The object at the top of the stack. @throws EmptyStackException if the stack is empty before the operation. */ public T pop(); /** Retrieves this stack's top entry. @return The object at the top of the stack. @throws EmptyStackException if the stack is empty. */ public T peek(); /** Detects whether this stack is empty. @return True if the stack is empty. */ public boolean isEmpty(); /** Removes all entries from this stack. */ public void clear(); } // end StackInterface Solution StackTester.java public class StackTester { public static void main(String[] args) { ArrayStack aS = new ArrayStack();
  • 3. aS.push(3); aS.push(5); aS.push(10); aS.push(11); System.out.println(""+ aS.peek() + ", " + aS.pop() + ", " + aS.peek2()); aS.remove(1); } } ArrayStack.java import java.util.Arrays; public class ArrayStack implements StackInterface { private T[] stack; private int topIndex; private boolean initialized = false; private static final int DEFAULT_CAPACITY = 50; private static final int MAX_CAPACITY = 10000; public ArrayStack() { this(DEFAULT_CAPACITY); } public ArrayStack(int initialCapacity) { checkCapacity(initialCapacity); @SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; stack = tempStack; topIndex = -1; initialized = true;
  • 4. } public boolean isEmpty() { return topIndex < 0; } private void ensureCapacity() { if(topIndex == stack.length - 1) { int newLength = 2*stack.length; checkCapacity(newLength); stack = Arrays.copyOf(stack, newLength); } } private void ensureCapacity(int n) { // add n slots to the array if(topIndex == stack.length - 1){ int newLength = 2*stack.length + n; checkCapacity(newLength); stack = Arrays.copyOf(stack, newLength); } } private boolean checkCapacity(int capacity) { boolean bool = true; if(capacity > MAX_CAPACITY) bool = false; return bool; } private boolean checkInitialized()
  • 5. { return initialized; } public void push(T newEntry) { checkInitialized(); ensureCapacity(); stack[topIndex+1] = newEntry; topIndex++; } public T pop() { checkInitialized(); if(!isEmpty()) { T top = stack[topIndex]; stack[topIndex]= null; topIndex --; return top; } else { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } } public T peek() { checkInitialized(); if(isEmpty()) { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } else
  • 6. return stack[topIndex]; } public void clear() { stack = (T[]) new Object[DEFAULT_CAPACITY]; topIndex = -1; } public T peek2() { checkInitialized(); if(isEmpty()) { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } else return stack[topIndex-1]; } public String toString() { String s = ""; for(int i = 0; i < stack.length; i++) { s += stack[i] + ","; } return s; } public void remove(int n) { checkInitialized(); if(n <= topIndex) { for(int i = n; i < (topIndex - 1); i++)
  • 7. { stack[i] = stack[i+1]; } } } public void pushAll(T[] a) { checkInitialized(); checkCapacity(topIndex + a.length); ensureCapacity(a.length); for(int i = 0; i < a.length; i ++) { stack[topIndex + 1] = a[i]; topIndex ++; } } } StackInterface.java public interface StackInterface { /** Adds a new entry to the top of this stack. */ public void push(T newEntry); /** Removes and returns this stack's top entry.*/ public T pop(); /** Retrieves this stack's top entry. */ public T peek(); /** Detects whether this stack is empty. */ public boolean isEmpty(); /** Removes all entries from this stack. */
  • 8. public void clear(); public T peek2(); // Returns the element below the top element, or throw an exception if there are less than two elements public String toString(); // Returns a string that shows all of the elements on the stack. You can choose the format. public void remove(int n); // removes the top n entries from the stack. Stops as soon as the stack is empty. public void pushAll(T[] a); // pushes each element in the array , beginning with index 0. }