I have arry of MyClass
MyClass[] data;
setting length:
data = new MyClass[1];
adding data:
data[0] = new MyClass();
Now I need to clear array. What is the best way to do this? Is it ok to assign null to that array?
data=null;
Do you want the array to still exist but have nothing in it? Reinitialise the array:
data = new MyClass[1];
Do you want the array to no longer exist, so that the garbage can be collected when the JVM feels like it? Then data=null; as you said.
If you have more than one reference to the same array and want to remove all elements:
Arrays.fill(data, null);
data to something new in both cases.Basically you don't need it in Java, you have automatic garbage collection.
Sometimes if you use Factories that store static data, sure, you need set it to null to prevent additional usage in the future
But if you looking for other ways you can try:
List<MyClass> data = new ArrayList<MyClass>(1);
data.add(new MyClass());
data.clear();
It depends, it all comes down to how the garbage collector handles it. You can do two things and the behavior and semantic is slightly different:
data[0] = null;
means that data will still keep referencing an area of memory containing a one-sized list of references to MyClass, only in this case the reference to MyClass is null. The garbage collector will collect the previously assigned instance of MyClass.
data = null;
however, will remove the mentioned area of memory altogether, and the garbage collector will collect both the list of references and the MyClass instance. So, from a memory standpoint, and if you really don't plan to use the same array of references, the second option will provide the most benefit.
null.data=null;just sets the reference tonull, and will make the array object itself subject to garbage collection, at which point you don't worry about it anymore. This is different than emptying the array of data but keeping the array object itself intact and referenced.