• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

OO, Equality\Comparable with Composition.

 
Greenhorn
Posts: 2
IBM DB2 Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,

 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Quick! Before anybody notices! Cover it up with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic