Thursday, June 12, 2014

Java Stack Implementation

This is a the simplest example of stack implementation in Java. 'Must-do' exercise for a junior software guys

public class Stack<T> {

 T[] items;

 int index = 0;

 @SuppressWarnings("unchecked")
 public Stack(int size) {
  items = (T[]) new Object[size];
 }

 public void push(T item) {
  if (index < items.length) {
   items[index] = item;
   ++index;
  } else {
   throw new StackOverflowError(
     "Element couldn't be added: stack is full. ");
  }
 }

 public T pop() {
  if (index > 0) {
   --index;
   T value = items[index];
   items[index] = null;
   return value;
  } else {
   return null;
  }
 }
 
 public boolean isFull() {
  return index == items.length;
 }
 
 public boolean isEmpty() {
  return index == 0;
 }
 
 
 public String toString() { /* Optional */
  StringBuilder sb = new StringBuilder();
  for (int iter = 0; iter < items.length; ++iter) {
   sb.append(items[iter] + " ");
  }
  return sb.toString();
 }

}

No comments:

Post a Comment