Create a stack structure in Java

Description

The following code shows how to create a stack structure.

Example


//w  w w  . ja v a2 s  .  c om
class Stack {
  private int maxSize;

  private double[] stackArray;

  private int top;

  public Stack(int s) {
    maxSize = s;
    stackArray = new double[maxSize];
    top = -1; 
  }

  public void push(double j) {
    stackArray[++top] = j;
  }

  public double pop() {
    return stackArray[top--];
  }

  public double peek() {
    return stackArray[top];
  }

  public boolean isEmpty() {
    return (top == -1);
  }

  public boolean isFull() {
    return (top == maxSize - 1);
  }
}

public class Main {
  public static void main(String[] args) {
    Stack theStack = new Stack(10);
    theStack.push(20);
    theStack.push(40);
    theStack.push(60);
    theStack.push(80);

    while (!theStack.isEmpty()) {
      double value = theStack.pop();
      System.out.print(value);
      System.out.print(" ");
    }
    System.out.println("");
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet