aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 24166
    
  30

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: 24166
    
  30

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
Anonymous Arrays
command line arguments
Array : Multi-dimensional
Array