we have to design a UML in java Implement the stack ADT in a Stack class. The st
ID: 3856057 • Letter: W
Question
we have to design a UML in java
Implement the stack ADT in a Stack class. The stack will hold integers (ints). For the implementation, use a fixed size array (not the ArrayList class). Implement the following methods: 1. the no-arg constructor initializes a stack with a default capacity of 4, i.e. the stack can take 4 elements at most), 2. a constructor that initializes a stack with a specific capacity (given as parameter), 3. push (adds a new element to the stack if it is not full), 4. pop (removes the last element from a stack if it is not empty). 5. peek (if the stack is not empty, returns the value of the last element from a stack, but does not remove the element from the stack), 6. getSize (returns how many elements are currently in the stack), 7. getCapacity (returns the capacity of the stack), 8. isFull (returns true if the stack is full), 9. isEmpty (returns true if the stack is empty). 10. toString (returns a string of all the elements). Optional (for bonus points): 11. equals (compares the stack with another stack given as parameter and returns true if both are of equal capacity and have the same elements in the same positions), 12. a constructor that copies another stack given as parameter, B. Design the Stack class using a UML diagram.Explanation / Answer
Here is the Java implementation of the Stack ADT described in the question. Bonus part is also done.
public class Stack {
private int data[];
private int capacity; //max no of elements
private int size; //the current no. of elementss
public Stack(){
this(4);
}
public Stack(int cap)
{
capacity = cap;
data = new int[capacity];
size = 0;
}
public boolean push(int val)
{
if(size == capacity)
return false;
else
{
data[size] = val;
size++;
return true;
}
}
public void pop()
{
if(!isEmpty())
{
size--;
}
}
public int peek()
{
if(!isEmpty())
return data[size-1];
return -1; //what should be returned if empty ?
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public boolean isFull()
{
return size == capacity;
}
public boolean isEmpty()
{
return size == 0;
}
public String toString()
{
String str = "[ ";
for(int i = size - 1; i >= 0; i--)
{
if(i != 0)
str += ", ";
str += data[i];
}
str += " ]";
return str;
}
//bonus points
public boolean equals(Stack other)
{
if(other == null || size != other.size)
return false;
for (int i = size-1; i >= 0; i--)
if(data[i] != other.data[i]) //no match
return false;
return true;
}
public Stack(Stack other)
{
if(other == null)
return;
else
{
data = new int[other.data.length];
size = other.size;
capacity = other.capacity;
for(int i = 0; i < size; i ++)
data[i] = other.data[i];
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.