This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, was wonder how Equality\Comparable would work with a composite object. I've I use the code below as an example (I've omitted the hashCode to keep code short).
So say I would like to keep a Set<Stock> so it is not possible to keep duplicate items. From the example, yes I could use inheritance but I'm just wondering how in general if composition was used, if the code is good/bad way of doing things.
The answer depends a bit on the answer to a philosophical question: what does equality mean?
One general answer that is used a lot is that equality means all the member variables pass the equals() test. For simple variables, you just test .equals() for each one.
For contained objects, you do .equals() on each object contained.
This still leaves philosophical questions. Suppose your object contains a Set. This interface can be backed/implemented by any of a number of concrete sets. TreeSet, HashSet, ImmutableSet, etc. Plus, the TreeSet can have different Comparators. So if one object contains say a TreeSet in ascending order, and another has a TreeSet in descending order, but both have elements that pass the .equals() test inside a for() loop, are they equal?