vico
vico

Reputation: 18251

The best way to empty array in java

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;

Upvotes: 2

Views: 13003

Answers (5)

Jose Cifuentes
Jose Cifuentes

Reputation: 596

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.

Upvotes: 0

dwarduk
dwarduk

Reputation: 949

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);

Upvotes: 7

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

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();

Upvotes: 1

Ami
Ami

Reputation: 4259

I dont know what you expecting.In general java have automatic garbage collection.

Arrays.fill(myArray, null);

Upvotes: 5

Quillion
Quillion

Reputation: 6476

Yes you can use = null and it will take care of things.

Once there is no variable pointing to the data, then garbage collector will collect it, and everything will be fine and dandy :)

Upvotes: 0

Related Questions