• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How can i delete an element in a Array ?

 
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


How can i delete an element in a Array ?

Please help
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great Explanation .Thanks
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic