| 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: 24039
|
|
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: 24039
|
|
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.
|
 |
 |
|
|
subject: How can i delete an element in a Array ?
|
|
|