0

我正在阅读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?
    }

}
4

1 回答 1

3

// TODO: mArrayList = null 以防止内存泄漏。有必要这样做吗?

不,活动对象及其成员如mArrayList可以被垃圾收集。您的活动代码不会显示任何会使对象引用过长的内容。

于 2013-06-04T07:57:27.857 回答