Part 1 Design and implement a generic stack class StackUMUC<T> and a generic que
ID: 3758889 • Letter: P
Question
Part 1
Design and implement a generic stack class StackUMUC<T> and a generic queue class QueueUMUC<T> (these names are chosen as to avoid confusion with similar classes defined in JDK).
For StackUMUC<T> class, implement the following methods:
StackUMUC(int) // class constructor
void push(T)
T pop()
T peek()
String toString()
For QueueUMUC<T> class, implement the following methods:
QueueUMUC(int) // class constructor
void put(T)
T get()
T peek()
String toString()
The source code of the two classes should compile without errors.
Part 2
Test the two classes StackUMUC<T> and QueueUMUC<T> for the JDK types Integer and String and for the user defined type Point. The class Point represents 2D Cartesian points having x and y as instance variables, a constructor with arguments, and the methods getX, getY and toString.
The programs should compile without errors.
Explanation / Answer
While implementing stack in Java, there are two choices: one is array based implementation, and second is linked implementation. Here we will implement stack in Java using arrays in object oriented way.
Stack Interface
As Java is an object oriented programming language so we will harness object oriented features of the language during implementation of stack in Java. In order to make end user independent from implementation details of the stack implementation in Java whether it is implemented using array or linked list, we define an interface Stack as follows. The following Stack interface can be assigned any object that implements this interface no matter the underlying implementation uses Array based or linked list based implementation.
Array of Generics in Stack Data Structure
During stack implementation in Java, inside the ArrayStack() constructor you will find that an array of ten items of type Object is being created and then it is casted to generic type Item. Could we have created generics array as container = new Item[10]; rather than the way we implemented in ArrayStack? The answer is NO; Java does not allow generic array creation