GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes What's the best way to clear an array. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic
Author

What's the best way to clear an array.

Paul Carter
Ranch Hand

Joined: Sep 20, 2006
Posts: 57
Am trying to write a little game to teach myself Java.

The game has an array of players and values, and restarts once it has completed.

I set up an array of Player objects at the start of the game (shown in the code snippet below), but am not sure how best to destroy the Player array so that I can load the players again.

Any advice?


public void loadPlayers(){
players = new Player[NUMPLAYERS];

for (int i=0; i<players.length; ++i) {
players[i] = new Player();
}
}
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
Unless you need to zero out the memory for security reasons or whatever, all you need to do is create another array with the existing array reference.

When the old array no longer has any references to it, it is eligible for garbage collection.


"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
If you still want to clear an array, look into the Arrays class doc. There are methods to fill part or all of the array with a specified value.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
GeeCON Prague 2014
 
subject: What's the best way to clear an array.