public class Stack {
private Object[] elements;
private int size;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack(){
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e){
ensureCapacity();
elements[size++] = e;
}
public Object pop(){
if(size==0){
throw new EmptyStackException();
}
return elements[--size];
}
private void ensureCapacity() {
if (elements.length==size){
elements = Arrays.copyOf(elements,2*size+1);
}
}
}
複製程式碼
以上的程式碼存在記憶體洩漏,當Stack的size先增大後減小時,一些不用的物件就會常駐記憶體。 修改後
public Object pop(){
if(size==0){
throw new EmptyStackException();
}
Object result = elements[--size];
elementss[size] = null;
return result;
}
複製程式碼