0
|
1 package example2;
|
|
2
|
1
|
3 /**
|
|
4 * 実行させてもMemory Leakはしません
|
|
5 * 参照が残り続けるStackなのでたくさん生成するといつかMemory Leakを起こす
|
|
6 */
|
|
7
|
0
|
8 public class MyStack {
|
|
9 private Object[] stack;
|
|
10 private int size = 0;
|
|
11 private static final int MAX_SIZE = 16;
|
|
12
|
|
13 public MyStack() {
|
|
14 this.stack = new Object[MAX_SIZE];
|
|
15 }
|
|
16
|
|
17 public void push(Object e) {
|
|
18 if (size==MAX_SIZE) return;
|
|
19 stack[size++] = e;
|
|
20 }
|
|
21
|
|
22 public Object pop() {
|
|
23 if (size == 0) {
|
|
24 return null;
|
|
25 }
|
|
26 return stack[--size];
|
|
27 }
|
|
28
|
|
29 private void print() {
|
|
30 for (Object o : this.stack) {
|
|
31 if (o == null) {
|
|
32 System.out.print("n ");
|
|
33 } else {
|
|
34 System.out.print(o + " ");
|
|
35 }
|
|
36 }
|
|
37 System.out.println();
|
|
38 }
|
|
39
|
|
40 public static void main(String[] args) {
|
|
41 MyStack s = new MyStack();
|
|
42
|
|
43 System.out.print("First:");
|
|
44 s.print();
|
|
45
|
|
46 for (int i = 0; i < 10; i++) {
|
|
47 s.push(Integer.valueOf(i)); // push
|
|
48 }
|
|
49
|
|
50 System.out.print("push: ");
|
|
51 s.print();
|
|
52
|
|
53 for (int i = 0; i < 10; i++) {
|
|
54 s.pop();
|
|
55 }
|
|
56
|
|
57 System.out.print("pop: ");
|
|
58 s.print();
|
|
59 }
|
|
60 } |