| Author |
emptying an array
|
David J Evans
Greenhorn
Joined: Apr 28, 2006
Posts: 11
|
|
Hi guys, Just wondering if there is a simple way to empty an array in java, without explicitly delcaring like myArray[n] = null...it's not really critical, as obviously I can write a quick function to iterate through and do it, but I was just curious to know if there is a function to just destroy the whole damn thing...kinda like the unset() function in PHP. Thanks.
|
 |
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
|
|
|
What about using Arrays.fill(array[],value)?
|
 |
David J Evans
Greenhorn
Joined: Apr 28, 2006
Posts: 11
|
|
|
Thanks for the suggestion - but I can't understand how to set all the values to null...all I can see (as far as I understand from the method descriptions), are ways to set the values in the array to a char/boolean/int etc...
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
|
null (a special kind of object reference) is covered by fill(Object[] a, Object val).
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
David J Evans
Greenhorn
Joined: Apr 28, 2006
Posts: 11
|
|
Hi guys, sorry to be a pain, but I just can't work out how to use this...can you give me the code example of how to fill a 10 space array with a null value for each space. Thanks.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Try writing some code to experiment with this: Create a new Object array.Use Arrays' fill method to fill the array with new Object instances.Iterate through the array and print each element to verify that you have Objects.Use Arrays' fill method to fill the same array with null references.Iterate through the array and print each element to verify that you have nulls.If you're having problems with this, show us your code.
|
 |
David McCombs
Ranch Hand
Joined: Oct 17, 2006
Posts: 212
|
|
A simple way would be just to create another array with the same size as the old one: Integer[] myArray = new Integer[10]; ... myArray = new Integer[myArray.length]; Is this better then using Arrays.fill() or looping through each element, setting it to null? I am not sure, but it is easy enough to test.
|
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
What kind of array are you using? If you have declared an array of ints (int[]), then you CANNOT use null as a value. The null value is only valid for object references. I think this is why you are confused. There is no way to "empty" an array of primitive values (such as int, char, etc.). Layne
|
Java API Documentation
The Java Tutorial
|
 |
 |
|
|
subject: emptying an array
|
|
|