Copy Code code as follows:
Import Java.util.Arrays;
/**
* Implementation of the Stack <br>
* @author Skip
* @version 1.0
*/
public class Stack<t> {
private int size; Number of elements in the stack
Private object[] arr; Underlying array
Private final int defaultlength = 200; Default length
/**
* Parameterless construction, initializing array with default length
*/
Public Stack () {
arr = new Object[defaultlength];
size = 0;
}
/**
* Initialize array with length parameter
* @param length
*/
public Stack (int length) {
arr = new Object[length];
size = 0;
}
/**
* Into the stack
* @param element data
*/
public void push (T element) {
Is there a need for expansion
if (size >= arr.length) {
Array expansion
Extendcapacity (size+1);
}
arr[size++] = element;
}
/**
* Out Stack
* @return Data
*/
@SuppressWarnings ("Unchecked")
Public T pop () {
The number of elements is 0 and the stack operation cannot be performed
if (size==0) {
return null;
}
T t = (t) arr[size-1];
Arr[--size] = null; Data is out of stack and restored to null
return t;
}
/**
* Empty 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
* Number of @return elements
*/
public int GetSize () {
return size;
}
/**
* Determine if the stack is empty
* @return Null is True, Non-null is False
*/
public Boolean IsEmpty () {
return size = = 0;
}
/**
* Print all the elements in the stack
*/
@SuppressWarnings ("Unchecked")
public void Printstack () {
for (int i=0;i<size;i++) {
System.out.print (((T) arr[i]). toString ());
}
System.out.println ();
}
/**
* Capacity Expansion
* @param length Required
*/
private void extendcapacity (int length) {
The current array length and the desired length are maximized
int mincapacity = Math.max (arr.length, length);
Determine if expansion is required
if (mincapacity-arr.length>0) {
Increase the length of the array by half
int newlength = arr.length + arr.length/2;
If the new length is smaller than the requirement, use the length of the requirement as the length of the array
if (Newlength < mincapacity) {
newlength=mincapacity;
}
Array length cannot exceed Integer.max_value
if (Newlength > Integer.max_value-8) {
Newlength = Integer.max_value;
}
Array expansion
arr = arrays.copyof (arr, newlength);
}
}
}