In hibernate manual it is said that you have to override the equals() and hashCode() methods if you intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations).
So the questions appeared:
Why is it a recommended way to represent many-value associations in a set?(Why shouldn't I use, let's say, ArrayList or LinkedList).
What happens behind the scene that I should override those methods only when I use Set?
equalsandhashCoderely on memory addresses to function (they are good for determining if two variables hold a reference to the sameObject). But, they don't actually determine anything beyond memory address. Normally you want to change that behavior. - Elliott FrischHashSetrelies onhashCodefor bucketing (andequalsfor identity). - Elliott FrischSetbecause of the contractual need to deduplicate elements. It is a good idea to do it for List too, in order that things like contains, retainAll, remove etc work as you expect. - Andy Turner