Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the best way to clear an array.

 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic