0
我正在閱讀名爲"Effective Java" by Joshua Bloch的書,並且有一段代碼會導致內存泄漏。Android內存泄漏了解
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);
}
}
的pop
方法應與
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
很顯然,我被替換。代碼(見下文)是否會導致內存泄漏?例如,我旋轉屏幕很多次,並且每次都分配內存。
public class MainActivity extends Activity implements OnClickListener {
private static final int CAPASITY = 10000;
private ArrayList<String> mArrayList = new ArrayList<String>(CAPASITY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Some work on mArrayList
}
@Override
public void onClick(View v) {
// Some work on mArrayList
}
@Override
protected void onDestroy() {
super.onDestroy();
// TODO: mArrayList = null to prevent memory leaks. Is it necessary to do it?
}
}
以哪種方式泄漏? – Blackbelt
@blackbelt,我編輯了這個問題。例如,在每個屏幕旋轉之後分配內存。 –
@RedPlanet,沒有內存泄漏,mArrayList將包含對新ArrayList的引用,並且不會引用舊的,因此它將被垃圾收集。對不起,對於offtopic,你讀了第二版嗎?你在莫斯科得到了什麼,它的成本是多少? – SpongeBobFan