This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
How can I delete an object from an Arraylist. I used the remove(Object obj) method to remove an object from a list and it is returning false. Also I print the size of the list after deleting the object. It is printing the same size before and after the remove method call.
Here are some possible problems with the remove() method on a List.
If you try to remove an object from a list while you're using an iterator on the list, the remove will fail. Use the remove method of iterator instead. Here's an example:
Another problem that might occur is misunderstanding the remove(Object o) method. When you pass an object to remove() instead of an index, the first object in the list that meets the criteria: listObject.equals(o) will be removed. For most classes you've created, this test will only be true if listObject and o are exactly the same instance of the class. To change this behavior, you must override the equals() method in the class to define equality between two instances of the class.
So, in your example, if you consider two instances of Book to be equal if they have the same ISBN property, you would override the equals(Object o) method that Book inherits from Object so that it returns true if the ISBN properties are the same. [ April 30, 2006: Message edited by: Merrill Higginson ]
My book class contains the instance variables as follows :-
int bookID; String bookTitle; String authorName; String classfication; int copies;
So how should I override the equals() method?
Joined: Feb 15, 2005
First of all, this link is a good article explaining all of the intricacies of overriding methods from java.lang.Object. It may be a little more information than you're looking for, though, so here's gist of it.
You decide what makes one book equal to another. If you've decided that as long as the bookID of one book is equal to the bookID of another book, they should be considered equal, then here's your method:
As the article explains, if you override equals, you should also override hashCode() as well. [ April 30, 2006: Message edited by: Merrill Higginson ]
Joined: Apr 30, 2006
Thanks Merrill... Now it's working fine. I have implemented the equals() override as you suggested. Thanks alot