Java实现自定义栈


package test.Stack;

/**       
 * @projectName:
 * @packageName: test.Stack
 * @ClassName  : ArrayStack
 * @createBy   :Test
 * @createDate :2014-6-11 上午09:33:25   
 * @useFor     : 自定义栈
 *    
 */

import java.util.Arrays;

public class ArrayStack implements IStack {
	private final int DEFAULT_SIZE = 3;
	private int size = 0;
	private int capacity = 0;
	
	//top指向下一个能够添加元素的位置
	private int top = 0;
	private Object[] array;
	
	public ArrayStack(){
		this.capacity = this.DEFAULT_SIZE;
		this.array = new Object[this.capacity];
		this.size = 0;
	}
	
	public ArrayStack(int capacity){
		this.capacity = capacity;
		this.array = new Object[this.capacity];
		this.size = 0;
	}
	
	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@SuppressWarnings("all")
	@Override
	public T peek() {
		return (T)this.array[this.top-1];
	}

	@SuppressWarnings("all")
	@Override
	public T pop() {
		T element = (T)this.array[top - 1];
		this.array[top--] = null;
		this.size--;
		return element;
	}

	@Override
	public void push(T element) {
		if(this.size < this.capacity){
			this.array[top] = element;
			this.top++;
			this.size ++;
		}else{
			enlarge();
			push(element);
		}
	}
	/**
	 * 
	 *@User   :Test
	 *@date   :2014-6-11 上午09:37:48
	 *@return :void
	 *@userFor : 扩容
	 */
	public void enlarge(){
		this.capacity = this.capacity + this.DEFAULT_SIZE;
		Object[] newArray = new Object[this.capacity];
		System.arraycopy(array, 0, newArray, 0, array.length);
		//把旧的array用null填充
		Arrays.fill(array, null);
		this.array = newArray;
	}
	
	public int size(){
		return this.size;
	}

	@Override
	public void clear() {
		Arrays.fill(array, null);
		this.top = 0;
		this.size = 0;
		this.capacity = this.DEFAULT_SIZE;
		this.array = new Object[this.capacity];
	}
	
	
	public static void main(String[] args) {
		ArrayStack stack = new ArrayStack();  
        stack.push(1);  
        stack.push(2);  
        stack.push(3);  
        stack.push(4);  
        stack.push(5);  
        System.out.println(stack.isEmpty());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.pop());  
        System.out.println(stack.size());  
        stack.clear();
        System.out.println(stack.size());  
	}
}


你可能感兴趣的:(Java实现自定义栈)