Stack Implementation with Array

Java Program to Show Stack Implementation

This java code implements stack functionality by using arrays. It can Pop and Push an item in stack with the help of array. The item can only be an integer number and internally the java program uses arrays to maintain items in stack.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class ArrayStack implements Stack
{

// Construct the stack.
public ArrayStack( )
{
  theArray = (AnyType []) new Object[ DEFAULT_CAPACITY ];
  topOfStack = -1;
}

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

public void makeEmpty( )
{
  topOfStack = -1;
}

public AnyType top( )
{
  if( isEmpty( ) )
    throw new UnderflowException( "ArrayStack top" );
  return theArray[ topOfStack ];
}

public void pop( )
{
  if( isEmpty( ) )
    throw new UnderflowException( "ArrayStack pop" );
  topOfStack--;
}

public AnyType topAndPop( )
{
  if( isEmpty( ) )
    throw new UnderflowException( "ArrayStack topAndPop" );
  return theArray[ topOfStack-- ];
}

// Insert a new item into the stack.

public void push( AnyType x )
{
  if( topOfStack + 1 == theArray.length )
    doubleArray( );
  theArray[ ++topOfStack ] = x;
}

// Internal method to extend theArray.
private void doubleArray( )
{
  AnyType [ ] newArray;

  newArray = (AnyType []) new Object[ theArray.length * 2 ];
  for( int i = 0; i < theArray.length; i++ )
    newArray[ i ] = theArray[ i ];
  theArray = newArray;
}

  private AnyType [ ] theArray;
  private int topOfStack;

  private static final int DEFAULT_CAPACITY = 10;
}

 

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post