This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How can i delete an element in a Array ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How can i delete an element in a Array ?" Watch "How can i delete an element in a Array ?" New topic
Author

How can i delete an element in a Array ?

PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212


How can i delete an element in a Array ?

Please help
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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[].


[Jess in Action][AskingGoodQuestions]
PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212
Great Explanation .Thanks
John Reese
Greenhorn

Joined: Apr 04, 2009
Posts: 7
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How can i delete an element in a Array ?
 
Similar Threads
Question on array conversion
command line arguments
Anonymous Arrays
Array
Array : Multi-dimensional