Search code examples
javaclassstackgeneric-programming

Generic Stack (Cracking the coding interview)


I have some problems in understanding the implementation of a Stack class in "Cracking the coding" interview (for those who have the book it is the first page of chapter 3 "Stack and Queues").

The code looks like this:

public class MyStack<T>{
  private static class StackNode<T>{
    private T data;
    private StackNode<T> next;
    public StackNode(T data){
      thid.data = data;
    }
  }
  private StackNode<T> top;
// and so on
}

The problem is that I really do not understand why I should use a generic type T for MyStack and the same for Stacknode. A stack is a "queue" of nodes, which are made of values. When I first tried to to this myself, I did something that looked more like:

class Stack{
  private static class Node{
    private Object data;
    private Node next;

    public Node(Object data){
      this.data = data;
    }
  }
  private Node top;

  public Stack(){
    top = null;
  }
  public Stack(Node top){
    this.top = top;
    top.next = null;
  }
//and so on
}

To me, MyStack<T> means I am creating an Object MyStack made of an other Object T, which does not make any sense. If a stack is made of Nodes, then my type T should be the type StackNode (???). But then, when I define Stacknode<T> it would be like saying Stacknode<Stacknode>. I think I making to much confusion with generic types, but the point is I do not understand why it is not sufficient doing like I did in my code: whatever sort of stack it is, it is made of nodes, which can then of course have a generic data, so I just said that the data of my Node is of type Object, can someone explain the main difference, or at least why in "Cracking the coding interview" it is done like this? What are the advantages? What am I understanding wrong? Thank you in advance!!


Solution

  • The purpose of the <T> here is to specify a type for the elements to be stored in the stack. Here T is kind of a template, which can be replaced by any type while being declared.

    For example, if you wish to create a stack of strings, you can declare it as

    Stack<String> myStack;
    

    This would ensure that the internal class Node would also use String as the data type of data. You'll just have to specify the type during the declaration of the stack and it should be good to go. This way you wouldn't have to write the Stack class again when you would need a stack of Integers.