• Post Reply Bookmark Topic Watch Topic
  • New Topic

Override Equals with Collections  RSS feed

 
TR Smith
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to determine a good methodology for writing an equals method when one of the member variables is actually a Collection of objects. The equals needs to really see if the items in the collection are equal. Per example, my class ABC holds a Collection of XYZ objects (XYZ class defines an equal method and appropriate hash code and implements Comparable).

Two ABC objects are equal if the Collections hold the same objects. I'm assuming I should check to see if either of the collections is null, size of collections, and then iterate through each collection list and compare against correspond object in other list (both sorted in some fashion).

I would then assume I should use the underly XYZ objects when overriding the hashCode method.

Any thoughts?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that most of the Java Collections already override equals() to include the requirement that all contained objects are equal; you therefore may just need to compare the Collection members of the two objects.
 
TR Smith
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting dilemna. My parent object A contains a Collection of objects B. B must always maintain a reference to A (A is a member variable). B is uniquely identified by it's String name within the context of its parent A (can only have one B object named Fred in A object alpha - can have another B object named Fred in A object bravo).

A objects are uniquely identified by their name AND their Collection of B objects.

B's equal method compares the name and then compares the A objects.
A's equal method compares the name and then the Collection.

When using a built in Collection compare method (such as Arrays.equals) for the A object, the compare method calls the B objects equals test. The B equals test calls the A objects equals method, The A object calls the B objects equals test....

Infinite loop. Or am I missing something (haven't tested it yet)?

Thanks for the help!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you'll get an infinite loop. You won't be able to use the built-in equals methods in this case.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!