| Author |
Deleting an entry from an array
|
Christopher Beech
Ranch Hand
Joined: Feb 08, 2006
Posts: 40
|
|
Ok. Kind of confused on how to delete an entry from an array. I know I need to search the array, but am not sure what to do afterwards. for(int i=0;i<directory.length;i++){ if(directory[i].equals(name)){ ??? So, can anybody give me a clue??? Danke!!!
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24041
|
|
First, the direct answer: you have two choices. You can either set the element you're deleting to null; this is OK if your program is written to allow null items in the array. Otherwise, if the order of the elements matters, you have to copy all the elements starting with the next higher numbered one down by one, then set the last element you copied to null, so there won't be two copies of it. If the order doesn't matter, you can cheat by just copying the very last element of the array on top of the the one you want to delete, then nulling out the last element. Second, the "real programmer" answer: there's rarely a reason in real programs to use arrays directly, at least not in this kind of situation. java.util.ArrayList is a wrapper around an array that handles inserting and deleting elements for you, so you don't have to worry about the details. [ February 09, 2006: Message edited by: Ernest Friedman-Hill ]
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: Deleting an entry from an array
|
|
|