(Revising Listing 19.1) Revise the GenericStack class in Listing 19.1 to implement it using an array rather than an ArrayList. You should check the array size before adding a new element to the stack. If the array is full, create a new array that doubles the current array size and copy the elements front the current array to the new array.
Revising Listing 19.1
Program Plan:
- Define the class named “GenericStack<E>”.
- Declare appropriate variables to program.
- Define constructors “GenericStack()” which assigns initial size of stack and “GenericStack(initialCapaciy)” which assigns size of the stack.
- Define a method “push()” which pass “E o” as parameter.
- Using “if” condition, check the value of “N” greater than “elements.length”.
- Assign size of new array.
- Copy old array into new array.
- Return array elements.
- Using “if” condition, check the value of “N” greater than “elements.length”.
- Define a method “pop()” which pop out stack elements.
- Return array elements.
- Define a method “peek()” which returns top of the stack.
- Define a method “isEmpty()” which returns “0”.
- Define a method “getSize()” which returns size of the stack.
- Define the main method.
- Declare the GenericStack object “obj”, using the object insert elements into stack.
- Using “while” loop, print the elements on screen.
The following JAVA code is to revise the “GenericStack” class which implements array rather than an “ArrayList”.
Explanation of Solution
Program:
//Class definition
class GenericStack<E>
{
/*Declaration of variables*/
public final static int INITIAL_SIZE = 16;
private E[] elements;
private int N;
/*Construct a stack with the default initial capacity */
public GenericStack()
{
//Assign initial size
this(INITIAL_SIZE);
}
/*Construct a stack with the specified initial capacity */
public GenericStack(int initialCapacity)
{
//Assign size
elements = (E[])new Object[initialCapacity];
}
/*Push a new element into the top of the stack */
public E push(E o)
{
//Condition
if (N >= elements.length)
{
//Assign array size into variable "t"
E[] t = (E[])new Object[elements.length * 2];
//Copy array elements
System.arraycopy(elements, 0, t, 0, elements.length);
//Assign "t" into "elements"
elements = t;
}
//Return statement
return elements[N++] = o;
}
/*Return and remove the top element from the stack*/
public E pop()
{
//Return statement
return elements[--N];
}
/*Return the top element from the stack */
public E peek()
{
//Return statement
return elements[N - 1];
}
/*Function definition to check empty*/
public boolean isEmpty()
{
//Return statement
return N == 0;
}
/*Return the number of elements in the stack */
public int getSize()
{
//Return statement
return N;
}
//Main method
public static void main(String[] args)
{
//Assign object to "GenericStack"
GenericStack<String> obj = new GenericStack<>();
//Push elements into stack
obj.push("London");
obj.push("Paris");
obj.push("Berlin");
//Print elements
System.out.print("Stack 1: ");
//Loop
while (!obj.isEmpty())
{
//Print statement
System.out.print(obj.pop() + " ");
}
//Print statement
System.out.println("\n");
}
}
Stack 1: Berlin Paris London
Want to see more full solutions like this?
Chapter 19 Solutions
Introduction to Java Programming and Data Structures, Comprehensive Version, Student Value Edition (11th Edition)
Additional Engineering Textbook Solutions
INTERNATIONAL EDITION---Engineering Mechanics: Statics, 14th edition (SI unit)
Introduction To Programming Using Visual Basic (11th Edition)
Mechanics of Materials (10th Edition)
Java: An Introduction to Problem Solving and Programming (8th Edition)
Web Development and Design Foundations with HTML5 (8th Edition)
Starting Out with Python (4th Edition)
- What should the next three steps be in my machine based home security system after deployment and after the following current steps: Enhancing Security & Privacy Measures User Interface (UI) and Experience (UX) Improvement Machine Learning Model Refinement & Continuous Improvementarrow_forwardI am creating a machine learning home based security system, have completed initial deployment and in the following phases of the project: Expanding device compatibility and integration, preparing for cloud integration, and implementing system reduncancy and disaster recovery. What should the next three phases be?arrow_forwardHands-On Assignments Part II Assignment 1-5: Querying the DoGood Donor Database Review the DoGood Donor data by writing and running SQL statements to perform the following tasks: 1. List each donor who has made a pledge and indicated a single lump sum payment. Include first name, last name, pledge date, and pledge amount. 2. List each donor who has made a pledge and indicated monthly payments over one year. Include first name, last name, pledge date, and pledge amount. Also, display the monthly payment amount. (Equal monthly payments are made for all pledges paid in monthly payments.) 3. Display an unduplicated list of projects (ID and name) that have pledges committed. Don't display all projects defined; list only those that have pledges assigned. 4. Display the number of pledges made by each donor. Include the donor ID, first name, last name, and number of pledges. 5. Display all pledges made before March 8, 2012. Include all column data from the DD PLEDGE table.arrow_forward
- Write a FancyCar class to support basic operations such as drive, add gas, honk horn, and start engine. FancyCar.java is provided with method stubs. Follow each step to gradually complete all methods. Note: This program is designed for incremental development. Complete each step and submit for grading before starting the next step. Only a portion of tests pass after each step but confirm progress. The main() method includes basic method calls. Add statements in main() as methods are completed to support development mode testing. Step 0. Declare private fields for miles driven as shown on the odometer (int), gallons of gas in tank (double), miles per gallon or MPG (double), driving capacity (double), and car model (String). Note the provided final variable indicates the gas tank capacity of 14.0 gallons. Step 1 (2 pts). 1) Complete the default constructor by initializing the odometer to five miles, tank is full of gas, miles per gallon is 24.0, and the model is "Old Clunker". 2)…arrow_forwardFind the error: daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] days_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(7): daily_sales[i] = float(input('Enter the sales for ' \ + day_of_week[i] + ': ')arrow_forwardFind the error: daily_sales = [0.0, 0,0, 0.0, 0.0, 0.0, 0.0, 0.0] days_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(7): daily_sales[i] = float(input('Enter the sales for ' \ + days_of_week[i] + ': ')arrow_forward
- Find the error: daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] days_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(6): daily_sales[i] = float(input('Enter the sales for ' \ + days_of_week[i] + ': '))arrow_forwardWhat are the steps you will follow in order to check the database and fix any problems with it and normalize it? Give two references with your answer.arrow_forwardWhat are the steps you will follow in order to check the database and fix any problems with it? Have in mind that you SHOULD normalize it as well. Consider that the database offline is not allowed since people are connected to it and personal data might be bridged and not secured. Provide three refernces with you answer.arrow_forward
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT
- New Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage LearningProgramming with Microsoft Visual Basic 2017Computer ScienceISBN:9781337102124Author:Diane ZakPublisher:Cengage LearningSystems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage Learning