假设我有以下Stack
课程(取自 Joshua Bloch 的Effective Java):
import java.util.Arrays;
public class Stack {
private Object[] elements;
private int size = 0;
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];
}
/**
* 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)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
我的问题是关于ensureCapacity
方法和Arrays.copyOf
JDK 方法:我们怎么能肯定旧的elements
数组对象可以被垃圾收集,因为copyOf
似乎正在创建一个新的数组对象?
换句话说,如果每次ensureCapacity
调用都创建一个新对象,那么旧对象去哪里了,不存在内存泄漏的风险吗?