File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Performance
Bookmark "Efficient way to compare complex objects?" Watch "Efficient way to compare complex objects?" New topic

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:
    subject: Efficient way to compare complex objects?
    It's not a secret anymore!