Question

In: Computer Science

Task Generics: GenericStack Class. Java. package Modul02; public class GenericStack<E> { private java.util.ArrayList<E> list = new...

Task Generics: GenericStack Class. Java.

package Modul02;

public class GenericStack<E> {

private java.util.ArrayList<E> list = new java.util.ArrayList<>();

public int size() {

return list.size();

}

public E peek() {

return list.get(size() - 1);

}

public void push(E o) {

list.add(o);

}

public E pop() {

E o = list.get(size() - 1);

list.remove(size() - 1);

return o;

}

public boolean isEmpty() {

return list.isEmpty();

}

@Override

public String toString() {

return "stack: " + list.toString();

}

}

package Modul02;

public class TestGenericStack {

public static void main(String[] args) {

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

gsString.push("one");

gsString.push("two");

gsString.push("three");

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

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

}

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

gsInteger.push(1);

gsInteger.push(2);

gsInteger.push(3);

//gsInteger.push("4");

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

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

}

}

}

Create a new version of GenericStack 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.
To create the generic array, a cast must:
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.

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

Solutions

Expert Solution

// GenericStack.java : Java program to create a Generic Stack using array

import java.util.Arrays;

public class GenericStack<T> {

       private T list[]; // array to contain the elements of stack

       private int top; // variable to contain the top index of stack

      

       // default constructor to create an empty stack of 100 elements

       public GenericStack()

       {

             list = (T[]) new Object[100];

             top = -1;

       }

      

       // method to return the top element of stack if not empty else it returns null

       public T peek() {

            

             if(!isEmpty())

                    return list[top];

             else

                    return null;

       }

      

       // method to push o to the top of stack , if o is not null

       public void push(T o) {

             if(o != null) // check if element to be inserted is not null

             {

                    if(top == (list.length-1)) //check if stack is full, then expand the stack by twice its size

                    {

                           list = Arrays.copyOf(list, 2*(list.length)); // copies the elements of the list and creates and returns a new array of size 2*list.length

                    }

                   

                    // push the element to top of stack

                    top++;

                    list[top] = o;

             }

       }

      

       // method to remove and return the element from top of stack if not empty else return null

       public T pop() {

             if(!isEmpty()) //check if stack is not empty

             {

                    // remove and return the top element

                    T o = list[top];

                    top--;

                    return o;

             }

            

             return null; // stack is empty

       }

      

       // method to check if the stack is empty

       public boolean isEmpty() {

             return(top == -1);

       }

      

       // method to return string representation of the stack

       public String toString()

       {

             String str = "Stack: [";

             for(int i=0;i<top;i++)

                    str += list[i]+", ";

             str += list[top]+" ] ";

             return str;

       }

}

//end of GenericStack.java

//TestGenericStack .java : Driver program to test the GenericStack

public class TestGenericStack {

       public static void main(String[] args) {

             // test the stack for string and integer type

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

             gsString.push("one");

             gsString.push("two");

             gsString.push("three");

             gsString.push(null); // this is not inserted

             System.out.println("Top element of Stack : "+gsString.peek());

            

             while(!gsString.isEmpty())

                    System.out.println("Removing element :"+gsString.pop());

             System.out.println("Trying to pop from an empty stack : "+gsString.pop()); // this should return null

            

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

             gsInteger.push(1);

             gsInteger.push(2);

             gsInteger.push(3);

             gsInteger.push(null); // this is not inserted

             System.out.println("Top element of Stack : "+gsInteger.peek());

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

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

             }

            

             System.out.println("Trying to peek from an empty stack : "+gsInteger.peek()); // this should return null

       }

}

//end of TestGenericStack.java

Output:


Related Solutions

NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task>...
NEed UML diagram for this java code: import java.util.ArrayList; import java.util.Scanner; class ToDoList { private ArrayList<Task> list;//make private array public ToDoList() { //this keyword refers to the current object in a method or constructor this.list = new ArrayList<>(); } public Task[] getSortedList() { Task[] sortedList = new Task[this.list.size()];//.size: gives he number of elements contained in the array //fills array with given values by using a for loop for (int i = 0; i < this.list.size(); i++) { sortedList[i] = this.list.get(i);...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Fill in the following blanks for java code::: import java.util.NoSuchElementException; public class CircularQueue<E> {    private...
Fill in the following blanks for java code::: import java.util.NoSuchElementException; public class CircularQueue<E> {    private E[] queue;    private int front = 0, rear = 0;    private static final int DEFAULT_CAPACITY = 5;       public CircularQueue(int capacity)    {    queue = (E[]) new Object[capacity + 1];    }       public CircularQueue()    {        this(DEFAULT_CAPACITY); }       //Add a method that will determine if the queue is empty. Recall that the queue is...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int size; public CircularLinkedList() { tail= null; size = 0; } public int size(){ return size; } public boolean isEmpty() { return size==0; } //if list is not empty return the first element public E first() { if (isEmpty()) return null; //code here return 0; } //if list not empty return last element public E last() { if (isEmpty()) return null; return tail.getElement(); } /*...
Create a Java class named Package that contains the following: Package should have three private instance...
Create a Java class named Package that contains the following: Package should have three private instance variables of type double named length, width, and height. Package should have one private instance variable of the type Scanner named input, initialized to System.in. No-args (explicit default) public constructor, which initializes all three double instance variables to 1.0.   Initial (parameterized) public constructor, which defines three parameters of type double, named length, width, and height, which are used to initialize the instance variables of...
Your Task: Starting with the following generic classes: public class LinkedListNode<E> { public E element; public...
Your Task: Starting with the following generic classes: public class LinkedListNode<E> { public E element; public LinkedListNode<E> next; } public class LinkedListBox<E> { public LinkedListNode<E> head; public int count = 0; } Create a LINKED LIST of random integers between 1 and 20. The program must prompt the user for the number of random integers to create before creating the list (i.e: if user asks for 40 integers then the program will link 40 integers between 1 and 20 generated...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private member variables that you need to declare: ** The head pointer ** The tail pointer */    private Node head;    private Node tail;       public class Node { // declare member variables (data and next)    Integer data;    Node next; // finish these constructors    public Node(int data, Node next) {               this.data=data;        this.next=next;    }...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
package dealership; public abstract class Vehicle { private float dealerPrice; private int year; public Vehicle(float d,...
package dealership; public abstract class Vehicle { private float dealerPrice; private int year; public Vehicle(float d, int y) { dealerPrice = d; year = y; } public float getDealerPrice() { return dealerPrice; } public int getYear() { return year; } public abstract float getStickerPrice(); } In the space below write a concrete class Car in the dealership package that is a subclass of Vehicle class given above. You will make two constructors, both of which must call the superclass constructor....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT