I implemented a stack data structure without using any libraries or Java API code.
@SuppressWarnings("unchecked")
public class Stack<E> {
// Properties
private E[] data;
private E[] buffer;
private int bufferSize;
// Constructor
public Stack() {
this.bufferSize = 0;
this.buffer = (E[]) new Object[this.bufferSize];
this.data = (E[]) new Object[this.bufferSize];
}
// Main methods
public boolean empty() {
return (bufferSize == 0);
}
public E peek() {
if (bufferSize == 0)
throw new ArrayIndexOutOfBoundsException("The stack is empty");
return this.data[this.bufferSize - 1];
}
public E pop() {
if (bufferSize == 0)
throw new ArrayIndexOutOfBoundsException("The stack is empty");
this.buffer = (E[]) new Object[this.bufferSize];
for (int i = 0; i < this.bufferSize; i++)
this.buffer[i] = this.data[i];
this.bufferSize--;
this.data = (E[]) new Object[this.bufferSize];
for (int i = 0; i < this.bufferSize; i++)
this.data[i] = this.buffer[i];
E object = buffer[this.bufferSize];
this.buffer = null;
return object;
}
public E push(E item) {
this.buffer = (E[]) new Object[this.bufferSize];
for (int i = 0; i < this.bufferSize; i++)
this.buffer[i] = this.data[i];
this.bufferSize++;
this.data = (E[]) new Object[this.bufferSize];
for (int i = 0; i < this.bufferSize - 1; i++) {
this.data[i] = this.buffer[i];
}
this.data[this.bufferSize - 1] = item;
this.buffer = null;
return item;
}
public int search(Object o) {
for (int i = this.bufferSize - 1; i >= 0; i--) {
if (this.data[i].equals(o))
return (this.bufferSize - i);
}
return -1;
}
public int size() {
return this.bufferSize;
}
}
You can tell me if the code is good or if it is in need of some improvement.