0

I have this method I use to remove a Book from the SetOfBooks class. I tried looping through and delete too, and googled too. This does not delete the Book object I'm passing and returns false,I cannot figure out where I'm going wrong. I wanted the method to remove the given object from the list. Please help. Thankyou

The following is the code of the where I call the removebook() method.

niki123
  • 43
  • 9
  • 1
    What's the actual problem? – Andy Turner Mar 11 '17 at 22:45
  • cannot delete the object I pass as the parameter – niki123 Mar 11 '17 at 22:47
  • 4
    I suspect you mean `public class SetOfBooks extends Vector {`, not `public class SetOfBooks extends Vector {`. In the latter case, `Book` is a type variable, not the `Book` class. – Andy Turner Mar 11 '17 at 22:48
  • 2
    I think that you will need to create and post a decent [mcve] to get a decent answer. Side issue: have you overridden equals and hashCode properly in your Book class? – Hovercraft Full Of Eels Mar 11 '17 at 22:48
  • 1
    `remove` is using `indexOf` to locate position of element, but `indexOf` is using `equals` method to determine if searched object is same as object which it is currently *looking at*. Problem is that if you don't override `equals` method in your Book it will be inherited from its superclass, which in your case is Object, and implementation used there simply uses `==` to see if two references are equal, not if two objects represent same state. – Pshemo Mar 11 '17 at 22:56
  • 1
    Yes, I was right -- you do not override those two key methods, equals and hashCode. Please read up on and then fix this problem. – Hovercraft Full Of Eels Mar 11 '17 at 22:57

1 Answers1

3

You probably did not override the equals (and hashcode) methods in your Book class.

Without overriding equals only the exact same object will be removed from a collection using remove.

dpr
  • 10,591
  • 3
  • 41
  • 71
  • When overriding `equals` and `hashCode` according to their contracts take special care for potentially mutable fields like `borrower`. With implementations for these methods autogenerated from your IDE all of those fields are included. If you have e.g. one place in code where you don't know the borrower and construct a book object in order to find or remove the "real" book which actually has a borrower this also won't work. – Markus Benko Mar 11 '17 at 23:03