我正在阅读Joshua Bloch 的《Effective Java》一书,其中有一段代码会导致内存泄漏。
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;
}
我很清楚。代码(见下文)会导致内存泄漏吗?例如,我多次旋转屏幕并private ArrayList<String> mArrayList = new ArrayList<String>(CAPASITY);
每次分配内存。
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?
}
}