aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes OO, Equality\Comparable with Composition. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "OO, Equality\Comparable with Composition." Watch "OO, Equality\Comparable with Composition." New topic
Author

OO, Equality\Comparable with Composition.

Kris Woo
Greenhorn

Joined: Sep 17, 2012
Posts: 2

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.

Thanks,

Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: OO, Equality\Comparable with Composition.