(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 (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)
- (Please Help. My professor did not teach us any of this and will not answer my emails) Design a class named Queue for storing integers. Like a stack, a queue holds elements. In a stack, the elements are retreived in a last-in-first-out fashion. In a queue, the elements are retrieved in a first-in-first-out fashion. The class contains: An int[] data field named elements that stores the int values in the queue A data field named size that stores the number of elements in the queue A constructor that creates a Queue object with defult capacity 8 The method enqueue(int v) that adds v into the queue The method empty () that returns true if the queue is empty The method getSize() that returns the size of the queuearrow_forwarda) Can you develop Java code.Create a recursive function to print all permutations of a string. For example, the permutation of the string "abc" is [abc, acb, bac, bca, cab, cba]. b) Revise the genericStack class to use an array instead of an ArrayList. Before adding a new element, make sure the array size is correct. If the current array is full, construct a new array twice the size, copy the elements, and add the new array. dont use aiarrow_forward[Java Code] The question SHOULD have MULTIPLE CLASSES like child, parent, main. Thank you in advance =Darrow_forward
- 6. the grade is under 20 which is outlier, remove it from the array list. 7. Print array list using System.out.println() 8. Use indexOf to print index of 80. 9. Use get function. 10. What is the difference between get and index of? 11. Print the values of the array list using Iterator class. 12.. Delete all the values of the array list using clear function. 13. Print all the values of the array after you execute clear using System.out.println(). what is the result of using clear function? 14. What is the shortcoming of using array List?arrow_forward(Intro to Java) Open a new Java file called ArrayMethods.java. Read the Javadoc comment for each method below and write the method according to the description in the comment Once you are getting the correct output for all tests inside of main, upload your source file to Canvas public class ArrayMethods { /** * Displays the contents of an array on the console * with each element separated by a blank space * Prints a new line character last * @param nums the array to print to the console */ public static void printArray(int[] nums) { return; } /** * Assuming an array of integers, return true if 1 * is the first element or 1 is the last element * Note: you may assume that you will be given an array * of at least length 1 * is1FirstLast([1, 2, 10]) → true * is1FirstLast([10, 1, 2, 1]) → true * is1FirstLast([13, 10, 1, 2, 3]) → false * @param numbers the array of int numbers * @return whether or not 1 is the first or…arrow_forwardName:- MIT Note:- Please type this java code and also need an output for this given Java program.arrow_forward
- (No java code/drawing) 1. Show the BST after inserting 15, 43, 100, 34, 23, 3, and 60 into an empty BST. 2. Show the BST after deleting 15 from the following BST. 3. Show the BST after deleting 60 from the following BST. 4. Show the inorder, preorder, and postorder of the following BST.arrow_forward(YOU ARE NOT ALLOWED TO USE ARRAYLIST IN THIS PROJECT)Write a Java program to simulate a blackjack game of cards. The computer will play the role of the dealer. The program will randomly generate the cards dealt to the player and dealer during the game. Cards in this game will be represented by numbers 1 to 13 with Ace being represented by a 1. Remember, that face cards (i.e. Jack, Queen, and King) are worth 10 points to a hand while an Ace can be worth 1 or 11 points depending on the user’s choice. The numbered cards are worth their number value to the hand.arrow_forwardThe disadvantage of array list is: (". a. The size of the array has to be decided from the beginning. b. There is a need to shift data to insert a new item in the list. O c. The space needed for the array is reserved from the beginning. O d. All.arrow_forward
- QUESTION 3 Save Answer Write the missing statements as per given comments to complete the programs. Java program for flexible array using ArrayList import java.util.ArrayList; import java.util.lterator, public class IteratorPatternDemo { public static void main(String args | DE I/ Define an object of ArrayList named as aryStack I| Add or push "Ahmed" on the top of aryStack i.e., at position 0 I| Add or push "Khalid" on the top of aryStack | Add or push "Majid" on the top of aryStack I/ Remove first name from aryStacki.e., from position 0 // Define an iterator "it" on aryStack I/ Write code to display all names in aryStack using the iterator • while( String obj = (String)it.next(): System.out.printin(obj): }}arrow_forwardsove by Java I1.7 (Shuffle ArrayList) Write the following method that shuffles the elements in an ArrayList of integers: public static void shuffle(ArrayList list)arrow_forward(Convert decimals to fractions)Write a program that prompts the user to enter a decimal number and displays the number in a fraction.Hint: read the decimal number as a string, extract the integer part and fractional part from the string, and use the Rational class in LiveExample 13.13 to obtain a rational number for the decimal number. Use the template athttps://liveexample.pearsoncmg.com/test/Exercise13_19.txt The problem can not use BigInteger //Below is the Rational LiveExample 13.13 that goes with the problem/question; notice "long" instead of "BigInteger" class Rational extends Number implements Comparable<Rational> { // Data fields for numerator and denominator private long numerator = 0; private long denominator = 1; /** Construct a rational with default properties */ public Rational() { this(0, 1); } /** Construct a rational with specified numerator and denominator */ public Rational(long numerator, long denominator) { long gcd = gcd(numerator,…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education