view src/example2/MyStack.java @ 1:0a4fdcd1ed46 default tip

minor change
author e095732
date Tue, 29 Jan 2013 15:27:43 +0900
parents 4dbea8e22628
children
line wrap: on
line source

package example2;

/** 
 * 実行させてもMemory Leakはしません
 * 参照が残り続けるStackなのでたくさん生成するといつかMemory Leakを起こす
 */

public class MyStack {
	private Object[] stack;
	private int size = 0;
	private static final int MAX_SIZE = 16;

	public MyStack() {
		this.stack = new Object[MAX_SIZE];
	}

	public void push(Object e) {
		if (size==MAX_SIZE) return;
		stack[size++] = e;
	}

	public Object pop() {
		if (size == 0) {
			return null;
		}
		return stack[--size];
	}
	
	private void print() {
		for (Object o : this.stack) {
			if (o == null) {
				System.out.print("n ");
			} else {
				System.out.print(o + " ");
			}
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		MyStack s = new MyStack();

		System.out.print("First:");
		s.print();

		for (int i = 0; i < 10; i++) {
			s.push(Integer.valueOf(i)); // push
		}

		System.out.print("push: ");
		s.print();

		for (int i = 0; i < 10; i++) {
			s.pop(); 
		}

		System.out.print("pop:  ");
		s.print();
	}
}