HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Simple array-based Stack class in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplestackarrayjavabasedclass

Problem

I have created a simple array-based Stack class with some methods like the actual Stack in Java.

I am testing this for mistakes, but since I am learning Java, my tests may not be as comprehensive as they should.

import java.util.*;

public class SJUStack {
    // Data Fields
    private E[] theData;
    private int topOfStack = -1;
    private static final int INITIAL_CAPACITY = 10;
    private int size = 0;
    private int capacity = 0;

    // Constructors
    public SJUStack(int initCapacity) {
        capacity = initCapacity;
        theData = (E[]) new Object[capacity];
    }

    public SJUStack() {
        this(INITIAL_CAPACITY);
    }

    // Methods
    public E push(E e) {
        if(size == capacity) {
            reallocate();
        }
        theData[size] = e;
        size++;
        topOfStack++;

        return e;
    } // End push(E e) method

    public E peek() {
        if(empty()) {
            throw new EmptyStackException();
        }
        return theData[topOfStack];
    } // End peek() method

    public E pop() {
        E result = peek();
        theData[topOfStack] = null;
        size--;
        topOfStack--;
        if(size = INITIAL_CAPACITY) {
            shrink();
        }
        return result;
    } // End pop() method

    public boolean empty() {
        return size == 0;
    } // End empty() method

    private void reallocate() {
        capacity *= 2;
        theData = Arrays.copyOf(theData, capacity);
    } // End reallocate() method

    private void shrink() {
        capacity /= 2;
        theData = Arrays.copyOf(theData, capacity);
    } // End shrink() method

    public String toString() {
        return Arrays.toString(theData);
    } // End toString() method

    public int size() {
        return size;
    } // End size() method
}

Solution

-
I suggest to use following method name: isEmpty() instead of empty()

-
If your Java version > 1.5 you should use @Override for your toString() method.

-
Do you really need the the article in class field name like theData?

-
You don't need both size and topOfStack variables. theData.size is enough.

Context

StackExchange Code Review Q#16426, answer score: 9

Revisions (0)

No revisions yet.