//?Can?you?spot?the?"memory?leak"?
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);
????}
}
這段代碼會(huì)發(fā)生內(nèi)存泄漏,無論我如何寫測試類,都沒有發(fā)生內(nèi)存泄漏。
1 回答

leiqjl
TA貢獻(xiàn)3條經(jīng)驗(yàn) 獲得超0個(gè)贊
當(dāng)你調(diào)用pop方法時(shí),彈出了這個(gè)對象,但棧內(nèi)部的數(shù)組還保留著這個(gè)引用。
添加回答
舉報(bào)
0/150
提交
取消