Developer's Daily Java Education - Test Projects
  front page | java | perl | unix | DevDirectory
   
Front Page
Java
Education
   
 



import java.util.EmptyStackException;

public class Stack1
{
  private Object[] elements;
  private int size = 0;

  public static void main(String[] args) throws InterruptedException
  {
    Stack1 s1 = new Stack1(2);
    s1.push(new String("This is a test of a potential memory leak scenario"));
    s1.push(new String("This is a test of a potential memory leak scenario"));
    s1.push(new String("This is a test of a potential memory leak scenario"));
    s1.push(new String("This is a test of a potential memory leak scenario"));
    s1.push(new String("This is a test of a potential memory leak scenario"));
    printMemoryInfo(1);
    s1.pop();
    printMemoryInfo(2);
    s1.pop();
    printMemoryInfo(3);
    s1.pop();
    printMemoryInfo(4);
    s1.pop();
    printMemoryInfo(5);
    Thread.sleep(3000);
    printMemoryInfo(10);
  }

  private static void printMemoryInfo(int i)
  {
    System.out.println(i);
    System.out.println("total: " + Runtime.getRuntime().totalMemory() );
    System.out.println("free : " + Runtime.getRuntime().freeMemory() );
  }

  public Stack1(int initialCapacity)
  {
    this.elements = new Object[initialCapacity];
  }

  public void push(Object o)
  {
    ensureCapacity();
    elements[size++] = o;
  }

  public Object pop()
  {
    if ( size == 0 ) throw new EmptyStackException();
    return elements[--size];
  }

  private void ensureCapacity()
  {
    if ( elements.length == size )
    {
      Object[] oldElements = elements;
      elements = new Object[2*elements.length+1];
      System.arraycopy(oldElements,0,elements,0,size);
    }
  }
}
Copyright © 1998-2003 DevDaily Interactive, Inc.
All Rights Reserved.