By setting an object to null, we marks it as able to be garbage collected. But to avoid bad surprises, we should also clear the collections. With a collections being part of java.util package, we can simply invoke clear method. But what to do in the case of arrays ? They are some possible solutions:
public class ClearArrayTest { @Test public void test() { // first case => set array's size to 0 if it's not final String[] arrayToClear = new String[] {"A", "B"}; arrayToClear = new String[0]; assertTrue("Array should be empty", arrayToClear.length == 0); // second case => fill nulls inside a final array; Thanks to it, all its objects will be garbage collectable final String[] otherArray = new String[] {"C", "D"}; Arrays.fill(otherArray, null); for (String letter : otherArray) { assertTrue("letter should be null", letter == null); } } }
Thanks to these methods, if any another objects points to the content of arrays, they will be garbage collectables and the arrays empty.