Question

Java.
Must not use Java API java.util.Stack

/**
A class of stacks whose entries are stored in an array.
Implement all methods in ArrayStack class using resizable
array strategy, i.e. usedoubleArray()

Must throw StackException during exception events in methods:
   peek(), pop(), ArrayStack(int initialCapacity)
Do not change or add data fields
Do not add new methods

*/

import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries p

/* Throw StackException if stack is empty / public T pop() // add stataments return null; // end pop public boolean empty) //

public interface StackInterface T> /Gets the current number of data in this stack @return the integer number of entries curre

public class StackException extends RuntimeException public StackException() this( public StackException(String errorMsg) s

import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static final int DEFAULT-CAPACITY = 50; / Construct a stack with DEFAULT_CAPACITY public ArrayStack() this (DEFAULTCAPACITY) > // end default constructor /* Construct a stack with the given initialCapacity * /* Throw StackException if initialCapacity0 public ArrayStack(int initialCapacity) // add stataments > // end constructor public void push(T newEntry) // add stataments // end push /* Throw StackException if stack is empty public T peek() // add stataments return null; > // end peek
/* Throw StackException if stack is empty / public T pop() // add stataments return null; // end pop public boolean empty) // add stataments return false; // end empty public int size() // add stataments return 0; > // end size public void clear() // add stataments 1 // end clear /toString) returns a list of data in Stack, separate them with'' public String toString() // add stataments return null; // double the size of array using Arrays.copyof () private void doubleArray() // add stataments // end doubleArray
public interface StackInterface T> /Gets the current number of data in this stack @return the integer number of entries currently in the stack* public int size); Adds a new data to the top of this stack. @param aData an object to be added to the stack / public void push (T aData); Removes and returns this stack's top data. @return the object at the top of the stack @throw StackException if the stack is empty* public T pop); / Retrieves this stack's top data. @return either the data at the top of the stack athrow StackException if the stack is empty public T peek); Detects whether this stack is empty @return true if the stack is empty */ public boolean empty) Removes all data from this stack public void clear) // end MyStackInterface
public class StackException extends RuntimeException public StackException() this("" public StackException(String errorMsg) super(errorMsg);
0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class ArrayStack<T> implements StackInterface<T> {

// Instance variables

private T[] stack; // Used to store the elements of this ArrayStack

private int topIndex; // Designates the first free cell

public static final int DEFAULT_CAPACITY = 50;

@SuppressWarnings("unchecked")

// Constructor

public ArrayStack(int capacity) {

if (capacity < DEFAULT_CAPACITY)

capacity = DEFAULT_CAPACITY;

stack = (T[]) new Object[capacity];

topIndex = 0;

}

// Returns true if this ArrayStack is empty

public boolean empty() {

// Same as:

// if ( top == 0 ) {

// return true;

// } else {

// return false;

// }

return (topIndex == 0);

}

// Returns the top element of this ArrayStack without removing it

public T peek() {

// pre-conditions: ! isEmpty()

if (empty())

return null;

return stack[topIndex - 1];

}

// Returns the 2nd top element of this ArrayStack without removing it

public T peek2() {

// pre-conditions: ! isEmpty()

if (empty() || topIndex - 2 < 0)

return null;

return stack[topIndex - 2];

}

// Removes and returns the top element of this stack

public T pop() {

// pre-conditions: ! isEmpty()

// pre-conditions: ! isEmpty()

if (empty())

return null;

if (topIndex < DEFAULT_CAPACITY) {

T[] temp = (T[]) new Object[topIndex];

for (int i = 0; i < topIndex; ++i) {

temp[i] = stack[i];

}

stack = temp;

}

// *first* decrements top, then access the value!

T saved = stack[--topIndex];

stack[topIndex] = null; // scrub the memory!

return saved;

}

// Puts the element onto the top of this stack.

public void push(Object element) {

// Pre-condition: the stack is not full

if (topIndex >= stack.length) {

T[] temp = (T[]) new Object[stack.length + DEFAULT_CAPACITY];

for (int i = 0; i < topIndex; ++i) {

temp[i] = stack[i];

}

stack = temp;

// *first* stores the element at position top, then increments top

stack[topIndex++] = (T) element;

} else {

// *first* stores the element at position top, then increments top

stack[topIndex++] = (T) element;

}

}

public String toString() {

String res = "";

for (int i = topIndex - 1; i >= 0; --i)

res = res + stack[i] + " ";

return res;

}

public T[] reverse() {

Object ob[] = new Object[topIndex];

for (int i = topIndex - 1; i >= 0; --i)

ob[i] = stack[i];

return (T[]) ob;

}

public boolean search(T p) {

Object ob[] = new Object[topIndex];

for (int i = topIndex - 1; i >= 0; --i)

if (stack[i].equals(p))

return true;

return false;

}

public boolean isFull() {

// TODO Auto-generated method stub

return topIndex >= stack.length;

}

public static void main(String args[]) {

ArrayStack<Integer> as = new ArrayStack<Integer>(26);

as.push(10);

as.push(20);

as.push(30);

as.push(10);

as.push(60);

as.push(70);

as.push(10);

as.pop();

as.pop();

as.pop();

System.out.println("Method Peek returns : " + as.peek());

as.push(10);

as.push(60);

as.push(70);

System.out.println(as.toString());

}

@Override

public int size() {

// TODO Auto-generated method stub

return topIndex;

}

@Override

public void clear() {

// TODO Auto-generated method stub

stack = null;

topIndex = 0;

}

}

=========================================
SEE output

152 public static void main(String args ArrayStack<Integer> as -new ArrayStack<Integer>(26); as.push(10); as.push(20); as.pus

Thanks, PLEASE COMMENT if there is any concern.

Add a comment
Know the answer?
Add Answer to:
Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT