import java.util.Arrays;
/*
模拟堆栈的存储方式
先入后出,后入先出
*/
class StackList{
int count = 0; //指针
Object[] element;
public StackList() {
this.element = new Object[3];
}
public void add(Object o){
ensureCapcity();
element[count++] = o;
}
public void ensureCapcity(){//判断当前数组是否够用
if(count==element.length){
int newLength = element.length*2;
element = Arrays.copyOf(element, newLength);
}
}
public Object pop(){//出栈为删除集合的元素,并且返回,删除是为了让垃圾回收器及时回收,防止内存泄露
int flag = --count;
Object o = element[flag];
element[flag] = null;
return o;
}
public int size(){
return count;
}
}
public class Dame1 {
public static void main(String[] args) {
StackList stackList = new StackList();
stackList.add("小明");
stackList.add("小光");
stackList.add("小刚");
stackList.add("小红");
int size = stackList.size();
for(int i = 0;i<size;i++){
System.out.println(stackList.pop());
}
}
}
/*
模拟堆栈的存储方式
先入后出,后入先出
*/
class StackList{
int count = 0; //指针
Object[] element;
public StackList() {
this.element = new Object[3];
}
public void add(Object o){
ensureCapcity();
element[count++] = o;
}
public void ensureCapcity(){//判断当前数组是否够用
if(count==element.length){
int newLength = element.length*2;
element = Arrays.copyOf(element, newLength);
}
}
public Object pop(){//出栈为删除集合的元素,并且返回,删除是为了让垃圾回收器及时回收,防止内存泄露
int flag = --count;
Object o = element[flag];
element[flag] = null;
return o;
}
public int size(){
return count;
}
}
public class Dame1 {
public static void main(String[] args) {
StackList stackList = new StackList();
stackList.add("小明");
stackList.add("小光");
stackList.add("小刚");
stackList.add("小红");
int size = stackList.size();
for(int i = 0;i<size;i++){
System.out.println(stackList.pop());
}
}
}