I have a doubt from the book Efective Java. The doubt is regarding equals method
reflexive rule violation. The book says the following:
“If you were to violate it and then add an instance of your class to a collection, the collection’s contains method would almost certainly say that the collection did not contain the instance that you just added.“
To test it I wrote an example class, but the contains method doesn’t return false It returns true. Can anybody tell what is the problem?
Reflexive means
x.equals(x)should returntruethis will return
false. And when you put it into a list and calllist.contains(foo)it will return false, because none of the elements in the list was equal to the one you passed. This is so becauselist.contains(..)iterates the elements and for each of them checksif (elem.equals(arg))See the docs of
Collection.contains(..)