Create a Generic Stack Class with generic parameter - Java Object Oriented Design

Java examples for Object Oriented Design:Generic Class

Description

Create a Generic Stack Class with generic parameter

Demo Code

import java.util.LinkedList;

class GenStack<E> {
  private LinkedList<E> list = new LinkedList<E>();

  public void push(E item) {
    list.addFirst(item);/* w w w . j a  v a  2  s  . com*/
  }

  public E pop() {
    return list.poll();
  }

  public E peek() {
    return list.peek();
  }

  public boolean hasItems() {
    return !list.isEmpty();
  }

  public int size() {
    return list.size();
  }

}

public class Main {
  public static void main(String[] args) {
    GenStack<String> gs = new GenStack<String>();

    System.out.println("Pushing four items onto the stack.");
    gs.push("One");
    gs.push("Two");
    gs.push("Three");
    gs.push("Four");

    System.out.println("There are " + gs.size() + " items in the stack.\n");

    System.out.println("The top item is: " + gs.peek() + "\n");

    System.out.println("There are still " + gs.size() + " items in the stack.\n");

    System.out.println("Popping everything:");
    while (gs.hasItems())
      System.out.println(gs.pop());

    System.out.println("There are now " + gs.size() + " items in the stack.\n");

    System.out.println("The top item is: " + gs.peek() + "\n");

  }
}

Related Tutorials