File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How do you empty an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do you empty an array?" Watch "How do you empty an array?" New topic

How do you empty an array?

john von
Ranch Hand

Joined: Apr 13, 2004
Posts: 49
How do you empty an array?
How about multiple array?
Rachel Swailes
Ranch Hand

Joined: May 18, 2004
Posts: 434
You can empty an array by running through it with a for loop and by assigning each place in the array to null or whatever your definitaion of empty is.

If it is an array of arrays then you need to run two for loops, one to loop through the outer array and one to loop through the inner arrays.

Try some code with these for loops and I'll help you out

karl koch
Ranch Hand

Joined: May 25, 2001
Posts: 388
why not just create a new one ?
if emptying an array is setting the elements to zero or null, then creating an new one might be faster ??
[ June 11, 2004: Message edited by: karl koch ]
john von
Ranch Hand

Joined: Apr 13, 2004
Posts: 49
Is there no shortcut to it?
What if i re-initialize it?

It the array "names" was not emptied through re-initialization, what will happen to the previous object "names" after it was re-intialize?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11957

you haven't really "emptied" the original array, you've created a second, new empty array and pointed your reference to it.

the first one is still there, but you can't get to it ever again. it will eventually be garbage-collected - although you have NO control over when that is done.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Note that another alternative (a better one, IMO) to the array-emptying "for" loop is to use the overloaded static "fill" methods in the java.util.Arrays class:

prints "null, null".

[Jess in Action][AskingGoodQuestions]
john von
Ranch Hand

Joined: Apr 13, 2004
Posts: 49
Thanks. I have a follow up question, but ill just create a new thread.

Thanks again!
I agree. Here's the link:
subject: How do you empty an array?
It's not a secret anymore!