Question

JUnit5 JAVA. Need help to make a unit test of my GenericStack.java code below. Feel free...

JUnit5 JAVA. Need help to make a unit test of my GenericStack.java code below. Feel free to change the code below to fit the task better. thanks :)

Assigment
Create a new version of GenericStack (Have started on the code below) that uses an array instead of an ArrayList (this version should also be generic). Be sure to check the size of the array before adding a new item; - if the array becomes full, double the size of the array, and you must copy elements from the old array to the new one.
Note that one cannot use the new operator on a generic type, new E is not allowed.
In order to create the array of the generic type, one must cast:
private E [] elements = (E[]) new Object[100];

Important that push checks that there is enough space, if not you have to double the stack size before push. Pushes should also not allow zero values ​​as arguments, because now they should only be ignored.

Tips: System.arraycopy (...); Public interface for the class is known, but start writing the tests first.

JUnit5(Unit test)
Write tests:
The tests will cover all scenarios (all possible ways you can use a stack). Since this is a generic class, test it for at least two different types (What if someone uses pop or peek on a blank stack?). Remember to include a test where the stack must be doubled to accommodate a new push (). Feel free to introduce a new public method capacity () that responds to the stack's current capacity. Also, create (if you haven't done) a constructor for the stack that takes in startup capacity (before you have one that creates a default capacity).


public class GenericStack {
    private E[] list = (E[])new Object[100];
    private int size = 0;

    /** Return the number of elements in the stack */
    public int getSize() {
        return size;
    }

    /** Return the top element from the stack */
    public E peek() {
        return list[size - 1];
    }

    /** Push a new element to the top of the stack */
    public void push(E o) {
        if (size >= list.length) {
            doubleList();
        }
        list[size++] = o;
    }

    /** Return and remove the top element from the stack */
    public E pop() {
        E o = list[--size];
        return o;
    }

    /** Test whether the stack is empty */
    public boolean isEmpty() {
        return size == 0;
    }

    /** Create a new array that is double the current array size
     * and copy the elements from the current array to the new array */
    private void doubleList() {
        E[] tempList = (E[])new Object[list.length * 2];
        System.arraycopy(list, 0, tempList, 0, list.length);
        list = tempList;
    }

    @Override // Override the toString array in the Object class
    public String toString() {
        return "stack: " + list.toString();
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi. I have answered this question before. Here is the completed code for this problem including modified GenericStack class. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: The JUnit test class is completely implemented. It will thoroughly test GenericStack objects of two types – Integer and String

// GenericStack.java

public class GenericStack<E> {

      // array

      private E[] array;

      // current size

      private int size;

      // initial capacity

      private final int DEFAULT_CAPACITY = 10;

      // constructor initializes an array of default capacity

      public GenericStack() {

            array = (E[]) new Object[DEFAULT_CAPACITY];

            // initializing size to 0

            size = 0;

      }

      // returns the size

      public int size() {

            return size;

      }

      // returns top element; or null if empty

      public E peek() {

            if (isEmpty()) {

                  // empty

                  return null;

            }

            // returning current top element

            return array[size - 1];

      }

      // adds an element to the top

      public void push(E o) {

            // preventing addition of null values

            if (o != null) {

                  // if array is full, doubling it

                  if (size == array.length) {

                        // creating new array of twice capacity

                        E[] newArr = (E[]) new Object[size * 2];

                        // copying array to newArr

                        System.arraycopy(array, 0, newArr, 0, array.length);

                        // replacing old array with new one

                        array = newArr;

                  }

                  // adding to index

                  array[size] = o;

                  // updating index

                  size++;

            }

      }

      // removes and returns the top element from stack, or null if empty

      public E pop() {

            if (isEmpty()) {

                  // empty stack

                  return null;

            }

            // getting element at top

            E element = array[size - 1];

            // updating size

            size--;

            // returning removed element

            return element;

      }

      // returns true if stack is empty

      public boolean isEmpty() {

            return size == 0;

      }

      @Override

      public String toString() {

            String str = "stack: [";

            // appending all elements of stack to a String

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

                  str += array[i];

                  if (i != size - 1) {

                        // appending a comma and space if this is not last element

                        str += ", ";

                  }

            }

            str += "]";

            return str;

      }

}

//modified TestGenericStack class to include more tests

public class TestGenericStack {

      public static void main(String[] args) {

            GenericStack<String> gsString = new GenericStack<String>();

            System.out.println("Current top element: " + gsString.peek());

            gsString.push("one");

            gsString.push("two");

            gsString.push(null); // will not be added since element is null

            gsString.push("three");

            System.out.println("Current top element: " + gsString.peek());

            System.out.println("popping until empty");

            while (!(gsString.isEmpty())) {

                  System.out.println(gsString.pop());

            }

            // attempting to pop an empty stack, should display null

            System.out.println("pop on empty stack: " + gsString.pop());

            GenericStack<Integer> gsInteger = new GenericStack<Integer>();

            System.out.println("Current top element: " + gsInteger.peek());

            // adding numbers from 1 to 20 to integer stack

            for (int i = 1; i <= 20; i++) {

                  gsInteger.push(i);

            }

            gsInteger.push(null); // will not be added since element is null

            System.out.println("Current top element: " + gsInteger.peek());

            while (!(gsInteger.isEmpty())) {

                  System.out.println(gsInteger.pop());

            }

            // attempting to pop an empty stack, should display null

            System.out.println("pop on empty stack: " + gsInteger.pop());

      }

}

// GenericStackTest.java (JUnit test)

import static org.junit.Assert.*;

import org.junit.Test;

public class GenericStackTest {

      // two GenericStack objects, one of Integer type and another of String type

      private GenericStack<Integer> intStack;

      private GenericStack<String> stringStack;

      @Test

      public void testGenericStackConstructor() {

            // ensuring that constructor creates an empty intStack

            intStack = new GenericStack<Integer>();

            assertEquals(intStack.size(), 0);

            assertEquals(intStack.isEmpty(), true);

            assertEquals(intStack.toString(), "stack: []");

            // doing the same for stringStack

            stringStack = new GenericStack<String>();

            assertEquals(stringStack.size(), 0);

            assertEquals(stringStack.isEmpty(), true);

            assertEquals(stringStack.toString(), "stack: []");

      }

      @Test

      public void testSize() {

            // ensuring that intStack size is 0 initially and increments after every

            // push operation

            intStack = new GenericStack<Integer>();

            assertEquals(intStack.size(), 0);

            intStack.push(1);

            assertEquals(intStack.size(), 1);

            for (int i = 1; i < 100; i++) {

                  intStack.push(i);

            }

            // after 100 valid push(), ensuring that size is 100

            assertEquals(intStack.size(), 100);

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

            assertEquals(stringStack.size(), 0);

            stringStack.push("1");

            assertEquals(stringStack.size(), 1);

            for (int i = 1; i < 100; i++) {

                  stringStack.push("" + i);

            }

            // after 100 valid push(), ensuring that size is 100

            assertEquals(stringStack.size(), 100);

      }

      @Test

      public void testPeek() {

            // ensuring that peek method always return top value, or null if

            // intStack

            // is empty

            intStack = new GenericStack<Integer>();

            assertEquals(intStack.peek(), null);

            intStack.push(1);

            assertEquals(intStack.peek(), (Integer) 1);

            intStack.push(999);

            assertEquals(intStack.peek(), (Integer) 999);

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

            assertEquals(stringStack.peek(), null);

            stringStack.push("1");

            assertEquals(stringStack.peek(), "1");

            stringStack.push("abc");

            assertEquals(stringStack.peek(), "abc");

      }

      @Test

      public void testPush() {

            // ensuring that push method always add elements to the top

            intStack = new GenericStack<Integer>();

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

                  intStack.push(i);

                  assertEquals(intStack.peek(), (Integer) i);

            }

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

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

                  stringStack.push(i + "");

                  assertEquals(stringStack.peek(), "" + i);

            }

      }

      @Test

      public void testPop() {

            intStack = new GenericStack<Integer>();

            // adding elements from 0 to 100 to intStack

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

                  intStack.push(i);

            }

            // ensuring that elements are popped in reverse order

            for (int i = 100; i >= 0; i--) {

                  assertEquals(intStack.pop(), (Integer) i);

            }

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

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

                  stringStack.push(i + "");

            }

            // ensuring that elements are popped in reverse order

            for (int i = 100; i >= 0; i--) {

                  assertEquals(stringStack.pop(), "" + i);

            }

      }

      @Test

      public void testIsEmpty() {

            // ensuring that isEmpty works as needed

            intStack = new GenericStack<Integer>();

            assertEquals(intStack.isEmpty(), true);

            intStack.push(1234);

            assertEquals(intStack.isEmpty(), false);

            intStack.pop();

            assertEquals(intStack.isEmpty(), true);

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

            assertEquals(stringStack.isEmpty(), true);

            stringStack.push("java");

            assertEquals(stringStack.isEmpty(), false);

            stringStack.pop();

            assertEquals(stringStack.isEmpty(), true);

      }

      @Test

      public void testToString() {

            // thoroughly testing toString method of the intStack

            intStack = new GenericStack<Integer>();

            assertEquals(intStack.toString(), "stack: []");

            intStack.push(1234);

            assertEquals(intStack.toString(), "stack: [1234]");

            intStack.push(999);

            assertEquals(intStack.toString(), "stack: [1234, 999]");

            intStack.push(0);

            assertEquals(intStack.toString(), "stack: [1234, 999, 0]");

            intStack.pop();

            assertEquals(intStack.toString(), "stack: [1234, 999]");

            intStack.pop();

            assertEquals(intStack.toString(), "stack: [1234]");

            intStack.pop();

            assertEquals(intStack.toString(), "stack: []");

            // doing similar test for stringStack

            stringStack = new GenericStack<String>();

            assertEquals(stringStack.toString(), "stack: []");

            stringStack.push("a");

            assertEquals(stringStack.toString(), "stack: [a]");

            stringStack.push("bb");

            assertEquals(stringStack.toString(), "stack: [a, bb]");

            stringStack.push("ccc");

            assertEquals(stringStack.toString(), "stack: [a, bb, ccc]");

            stringStack.pop();

            assertEquals(stringStack.toString(), "stack: [a, bb]");

            stringStack.pop();

            assertEquals(stringStack.toString(), "stack: [a]");

            stringStack.pop();

            assertEquals(stringStack.toString(), "stack: []");

      }

}

Add a comment
Know the answer?
Add Answer to:
JUnit5 JAVA. Need help to make a unit test of my GenericStack.java code below. Feel free...
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: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • 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...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    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 static...

  • Java/Queues ** Task: Write a JUnit test that shows a failure in some part of the...

    Java/Queues ** Task: Write a JUnit test that shows a failure in some part of the ADT -----ArrayQueue.java------- public class ArrayQueue {    private static final int INITIAL_CAPACITY = 2; // to permit easier testing    private Object[] contents;    private int front, rear;       /**    * Create an empty queue with an initial capacity.    */    public ArrayQueue() {        contents = new Object[INITIAL_CAPACITY];    }       /**    * Add an element to...

  • 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...

  • 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...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • 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...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

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