数组模拟堆栈的存储方式代码实践

堆栈的模式是先进后出,取出后堆栈中就没有取出的元素了,所以在模拟时候要注意这些问题。

 1 import java.util.Arrays;
 2 
 3 /*
 4  
 5 需求:编写一个类使用数组模拟堆栈的存储方式。  
 6 
 7 堆栈存储特点: 先进后出,后进先出。
 8 
 9 注意: 不再使用的对象,应该不要让变量指向该对象,要让该对象尽快的被垃圾回收期回收。
10 
11 
12  */
13 class StackList{
14     
15     Object[] elements;
16     
17     int index = 0 ; //当前的索引值
18     
19     public StackList(){
20         this.elements = new Object[3];
21     }
22     
23     //添加内容
24     public void add(Object o){
25         //添加元素之前应该要先检查是否容量够用。
26         ensureCapcity();
27         elements[index++] = o;
28     }
29     
30     
31     //出栈: 删除集合的元素,并且返回。
32     public Object pop(){
33         int tempIndex = --index;
34         Object o = elements[tempIndex];
35         elements[tempIndex] = null; //让该位置不再 引用着指定的对象,让垃圾回收期赶快回收该垃圾。
36         return o;
37     }
38         
39     //检查当前的数组使用够用。
40     public void ensureCapcity(){
41         if(index==elements.length){
42             //计算一个新的长度
43             int newLength =    elements.length*2;
44             elements = Arrays.copyOf(elements, newLength);
45         }
46     }
47     
48     //获取当前的元素 个数
49     public int size(){
50         return index;
51     }
52 
53 }
54 
55 public class Demo1 {
56 
57     public static void main(String[] args) {
58         StackList list = new StackList();
59         list.add("AA");
60         list.add("BB");
61         list.add("CC");
62         list.add("DD");
63     
64         int size = list.size();
65         for(int i = 0 ; i<size ; i++){
66             System.out.println(list.size() + "|" + list.pop());
67         }    
68     }
69 }

输出语句:System.out.println(list.size() + "|" + list.pop());分别输出当前堆栈的大小和堆栈顶端内容,那么输出结果如下:

4|DD
3|CC
2|BB
1|AA

因为每一次pop,并不是读内容,而是把内容取出来,所以每一次执行pop,堆栈都会少1。

原文地址:https://www.cnblogs.com/K-artorias/p/7351515.html