The stack is one of the most important data structures in the Java language, and its implementation should at least include the following methods:
1.pop () out stack operation, pop-up stack top element.
2.push (e e) stack operation
3.peek () View top of Stack element
4.isEmpty () stack is empty
In addition, to implement a stack, you should also consider several issues:
1. The initial size of the stack and how to add stack space after the stack is full
2. Update the stack needs to be synchronized
For a simple example, use an array to implement the stack with the following code:
Copy Code code as follows:
public class Stack<e> {
Java does not support generic arrays, if needed, use Java-provided containers
Private object[] Stack;
Default initial size of stack
private static final int init_size = 2;
Stack Top Index
private int index;
public Stack () {
stack = new Object[init_ size];
index = -1;
}
/**
* Construction method
*
* @param initsize
* Initial size of stack
*/
Public Stack (int initsize) {
if (initsize < 0) {
; throw new IllegalArgumentException ();
}
stack = new object[ initsize];
index = -1;
}
/**
* Out Stack operation
*
* @return Stack Top Object
*/
Public synchronized E Pop () {
if (!isempty ()) {
E temp = peek ();
stack[index--] = null;
return temp;
}
return null;
}
/**
* Into stack operation
*
* @param obj
* Waiting for the object to stack
*/
Public synchronized void push (E obj) {
if (Isfull ()) {
object[] temp = stack;
If the stack is full, create a stack with twice times the current stack space
stack = new object[2 * Stack.length];
System.arraycopy (temp, 0, stack, 0, temp.length);
}
Stack[++index] = obj;
}
/**
* View the top of the Stack object
*
* @return Stack Top Object
*/
Public E Peek () {
if (!isempty ()) {
Return (E) Stack[index];
}
return null;
}
/**
* See if the stack is empty
*
* @return Returns True if the stack is null or FALSE
*/
public Boolean IsEmpty () {
return index = = 1;
}
/**
* See if the stack is full
*
* @return returns False if the stack returns true if it is full
*/
public Boolean isfull () {
return index >= stack.length-1;
}
}
Finally, the Java implementation of the Stack (java.util.Stack) of the data structure, it is implemented by inheriting vector classes, in general, we use directly to the line.