File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Deleting an entry from an array Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Deleting an entry from an array" Watch "Deleting an entry from an array" New topic
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
    
  13

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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Deleting an entry from an array
 
Similar Threads
Please help interprete this code
Can't figure out the logic in this method
How Do I Create An Array That "Backs" a List?
Need An Idea to solve This
String indexing