• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How can i delete an element in a Array ?

 
PavanPL KalyanK
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How can i delete an element in a Array ?

Please help
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't, really. You can set the element to null or 0, or you can move all the other elements down by one and set the last element to null or zero. In either case, the array will still be the same size.

What you can do is allocate a new array one element shorter, and copy all the elements you want to keep into the new array.

If you don't like the way this sounds -- and you shouldn't! -- consider using a List<Integer> instead of an int[].
 
PavanPL KalyanK
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great Explanation .Thanks
 
John Reese
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We are being taught to keep track of the array length with an instance variable called 'count'.
So, whenever we removed something we shuffled everything down a notch and then we decremented the count.

public void removeThing(int index){

for(int i = index; i < things.length-1; i++){
things[i] = things[i + 1];
}

things[things.length-1]=null;
count--;
}

I'm a newb, so take this with a grain of salt.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Reese wrote:We are being taught to keep track of the array length with an instance variable called 'count'.


Indeed, it's good to understand how to do this. That's what ArrayList does for you, automatically.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic