Search code examples
javaadtabstract-data-type

Is my example a description for ADTs? (java)


I understand that ADTs (abstract data types) hide/abstract the implementation of a method. So, an interface is an ADT, correct? So my questions are:

  1. Is my example to illustrate the interface MyStack as an ADT and its implementation in the class ImplementationOfMyStack, correct?
  2. If question 1 is yes, then why is there a class Stack in Java Libraries? My confusion is that I can instantiate the class Stack to use push(), pop(), peek() without coding an implementation like my example does. So, I think the class Stack has its implementation and is therefore a data structure and not an ADT.
public interface MyStack {  
    public void push();
    public void pop();
    public void peek();
}
public class ImplementationOfMyStack implements MyStack {

    public void push() {
        System.out.println("Code an implementation here to push a new item on top.");
        System.out.println("The implementation is a data structure e.g. linked List.");
    }

    public void pop() {
        System.out.println("Code an implementation here to pop a new item from top.");
        System.out.println("The implementation is a data structure e.g. linked List.");
    }

    public void peek() {
        System.out.println("Code an implementation here to peek a new item from top.");
        System.out.println("The implementation is a data structure e.g. linked List.");
    }
    
}

Solution

    1. Yes an interface is an abstract data type.
    2. Your implementation is correct.
    3. There is always a Stack class in the java library. Stack is a generic data structure that represents a LIFO (last in, first out) collection of objects allowing for pushing/popping elements in constant time. (I would recommend to use the Deque interface. Deque defines a more complete and consistent set of LIFO operations.)