Sign in to follow this  
Xiachunyi

[java] Array List Compacting

Recommended Posts

Xiachunyi    556
Hello, I am currently writing a student registration program and have a specific problem I would like to address. I have an array list of student objects that can be manipulated during run-time. The student objects within the array list can be destroyed as well. My question is that if a student object is destroyed that is in position number 5 of the total 20, does the array list now have a hole or does the entire contents of that array list shift down? I tried searching on Google but I do not know how to exactly state it in search terms to be able to arrive at the correct answer. Thank you.

Share this post


Link to post
Share on other sites
Stani R    1070
From the JDK 1.5 API entry for ArrayList:

Quote:

public E remove(int index)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).



Edit: to more clearly address your issue: destroying the objects does nothing, since objects are only references. You will need to remove all references to an object to get rid of it and that includes calling YourArrayList.remove()

(ie, object will no longer be referenced = unreachable = marked for garbage collection)

Share this post


Link to post
Share on other sites
OrangyTang    1298
ArrayList.remove()

When you remove an element from the middle, the rest of the elements are shifted along. So if you're removing from the middle of a big arraylist then shifting could take some time. As long as order isn't important a trick you can do is to overwrite the one to be removed with the last element, then remove the last element. Careful doing this while iterating over the collection though. If you want lots of removals from the middle, LinkedList might be a better choice.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this