Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Deleting an entry from an array  RSS feed

 
Christopher Beech
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!