• 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 ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

Efficient way to compare complex objects?

Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
    Consider Paul's rocket mass heater.
      Bookmark Topic Watch Topic
    • New Topic