Adam Satyres wrote:
Jeanne Boyarsky wrote:
Adam Satyres wrote:When we want to compare 2 object we don't need to use hashcode, as it said in the book , hashcode used to improve the performance ?
I don't think you mean compare here. To compare, you use Comparable or Comparator which doesn't require implementing equals or hashCode.
this is the question do i have to override both always
You are making it too complicated. It is very simple really. Just remember the following two points:
1. You need to override equals if you want to customize the logic that makes two objects of a class equal. For example, you have a class named Account with two attributes name and number, you might want to override the equals method that checks whether the names as well as account numbers of both the objects match.
If you don't override equals methods, the default one provided by Object class will be used, which just checks if two reference point to the exact same object. It doesn't look into the contents of the objects (like we are doing above).
2. You need to override hashCode only if you want to store and then retrieve objects of your class in any contains that makes use of the hashCode. The name of the container class usually gives that away. For example, if you add Account objects to HashSet or HashMap, you have to override the hashCode method.
You should ask the question "why?" at this point and for that, this link should be helpful:
http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java
HTH,
Paul.