File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

OO, Equality\Comparable with Composition.

 
Kris Woo
Greenhorn
Posts: 2
IBM DB2 Eclipse IDE Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4660
5
Linux Mac OS X VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic