This content has been marked as final. Show 5 replies
What makes you think comparing the serialized form of an object is the proper way to test for equality?
I have a feeling there's something about the serialization process that I don't fully comprehend.I would agree with that.
Is there a way to properly implement object comparison using serialization?I wouldn't think so. In fact I wouldn't have thought it possible at all. The serialization process is incompatible with just about every notion of "equal" in Java. I would think you'd be better off just writing a proper equals(Object) method for your class.
the quick answer is: you cant
the longer answer is: you cant test object equality using serialization
Thanks for the prompt reply! This was an avenue we wanted to explore as our existing framework makes it difficult to compare objects otherwise (we have a bunch of aggregation/composition/backreferences and cyclic references that need to be handled by this framework). We were using a custom toString that used our framework to walk to object model before, but this proved to be a bit inefficient.
If possible, could you explain why object serialization fails?
When you serialize an object, you also serialize the entire tree of references based on that object (except for transient variables). That tree is the complicated business you described there. Serialization stores all the objects in the tree, along with data that explains which objects refer to which other objects. Furthermore if the tree is actually a graph, and there are multiple ways to get to an object, it still only stores each object once. I don't see any reason to believe that all that relationship data would be encoded identically for a pair of trees that you deemed to be equal. And your experiment shows that indeed it isn't.