aspose file tools*
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 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do you empty an array?" Watch "How do you empty an array?" New topic
Author

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

Cheers,
Rachel
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 ??
karl
[ 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
Bartender

Joined: Oct 02, 2003
Posts: 10929
    
  12

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
Marshal

Joined: Jul 08, 2003
Posts: 24168
    
  30

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: http://aspose.com/file-tools
 
subject: How do you empty an array?
 
Similar Threads
Problem with return statement....
Empty array
arrays
empty array[][] contents
Character Array Question in Core Java