wood burning stoves 2.0*
The moose likes Performance and the fly likes Efficient way to compare complex objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Efficient way to compare complex objects?" Watch "Efficient way to compare complex objects?" New topic
Author

Efficient way to compare complex objects?

Darien Cheung
Ranch Hand

Joined: Aug 13, 2004
Posts: 36
I'm looking for an efficient way to implement an equals() method for a complex object. My class contains Strings and integers and booleans, but also several List of other objects, which contain Strings and other Java objects. I think it would be slow to do a deep comparison, is there any way to generate a "checksum" so that I can use it to quickly compare? My objects might be built in different JVM so I'm worried that Hashcode may not be sufficient.
John Kimball
Ranch Hand

Joined: Apr 13, 2009
Posts: 96
It depends.

  • Would you generally expect differences or matches?
  • Are your lists private and only exposed by accessors?

  • Personally, I think a hashCode would be sufficient provided you're not dealing with serialization or persistence and you expect a number of differences.

    In that case, you only have to do a deep equals comparison when there's a hashCode collision.

    The lists could be problematic, but here's an easy solution:
  • Have an int instance for each list
  • Initialize the ints to -1 (FFFFFF...)
  • Everytime you add/remove something to the list, get that object's hashCode and XOR with the int


  • The XOR is important, because it's a fast and reversible operation.

    I can go into more detail, but I think you have enough to go on.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Efficient way to compare complex objects?