// Can you spot the "memory leak"? public class Stack { PRivate Object[] elements; private int size = 0;
public Stack(int initialCapacity) { this.elements = new Object[initialCapacity]; }
public void push(Object e) { ensureCapacity(); elements[size++] = e; }
public Object pop() { if (size==0) throw new EmptyStackException(); Object result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; }
/** * Ensure space for at least one more element, roughly * doubling the capacity each time the array needs to grow. */ private void ensureCapacity() { if (elements.length == size) { Object[] oldElements = elements; elements = new Object[2 * elements.length + 1]; System.arraycopy(oldElements, 0, elements, 0, size); } }
public static void main(String[] args) { Stack s = new Stack(0); for (int i=0; i<args.length; i++) s.push(args[i]); for (int i=0; i<args.length; i++) System.out.println(s.pop()); } }
总结:在拥有自动垃圾收集功能的语言里,我们要非凡注重内存治理的问题,因为这个时候内存的溢出问题不会象c plus plus这些那么明显。我们要防范于未然。另外,根据的经验,inputstreamreader等文件读写类,我们要在set 他们为null的之前,close他们的连接,即调用in.close().然后再in=null;(这里in是一个inputstreamreader等)。