The code copy is as follows:
import java.util.Arrays;
/**
*Stack Implementation<br>
* @author Skip
* @version 1.0
*/
public class Stack<T> {
private int size; //The number of elements in the stack
private Object[] arr;//The underlying array
private final int defaultLength = 200;//Default length
/**
* No parameter construct, initialize array with default length
*/
public Stack(){
arr = new Object[defaultLength];
size = 0;
}
/**
* Initialize the array with length parameters
* @param length
*/
public Stack(int length){
arr = new Object[length];
size = 0;
}
/**
* Enter the stack
* @param element data
*/
public void push(T element){
//Is it necessary to expand the capacity
if(size >= arr.length){
//Array expansion
extendCapacity(size+1);
}
arr[size++] = element;
}
/**
* Out of the stack
* @return data
*/
@SuppressWarnings("unchecked")
public T pop(){
//The number of elements is 0, and the stacking operation cannot be performed
if(size==0){
return null;
}
T t = (T)arr[size-1];
arr[--size] = null;//The data has been released and restored to null
return t;
}
/**
* Clear the stack
*/
public void clear(){
for(int i=0;i<size;i++){
arr[i]=null;
}
size = 0;
}
/**
* Get the number of elements in the current stack
* @return Number of elements
*/
public int getSize(){
return size;
}
/**
* Determine whether it is an empty stack
* @return Empty is true, non-empty is false
*/
public boolean isEmpty(){
return size == 0;
}
/**
* All elements in the print stack
*/
@SuppressWarnings("unchecked")
public void printStack(){
for(int i=0;i<size;i++){
System.out.print(((T)arr[i]).toString());
}
System.out.println();
}
/**
* Expand capacity
* @param length The required length
*/
private void extendCapacity(int length){
//The current array length and required length should be the maximum
int minCapacity = Math.max(arr.length, length);
//Judge whether capacity expansion is required
if(minCapacity - arr.length>0){
//Array length is increased by half
int newLength = arr.length + arr.length/2;
//If the new length is smaller than the requirement, use the required length as the array length
if(newLength < minCapacity){
newLength=minCapacity;
}
//The array length cannot exceed Integer.Max_Value
if(newLength > Integer.MAX_VALUE - 8){
newLength = Integer.MAX_VALUE;
}
//Array expansion
arr = Arrays.copyOf(arr, newLength);
}
}
}