Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Testing Object Equality using Serialization

807591Mar 7 2008 — edited Mar 7 2008
Hey everyone! I was wondering if somebody could help me figure out how to compare two objects using serialization.

I have two objects that I'm trying to compare. Both of these objects extend a common "Model" class that has a method getSerialized() that returns a serialized form of an instance, shown below:
		// Serialize the object to an array
	    ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
	    ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream(baos);
		    oos.writeObject(this);
		    oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    //Deserialize array into a String array
	    return baos.toByteArray();
This Model class also has an equals(Model obj) method that allows for the current model object to be compared to a model object that is passed in:
        //Store both models' serialized forms into byte arrays
        byte [] thisClass = this.getSerialized();
        byte [] otherClass = obj.getSerialized();
This is where things get a little funny. The byte arrays don't equal - one array is a byte larger than the other. If a byte-by-byte comparison is done, the arrays are equal for the first 15-20% and then not equal for the rest. If I deserialize the byte arrays back into Models and do a toString() on those models, I find that they are equal.

I have a feeling there's something about the serialization process that I don't fully comprehend. Is there a way to properly implement object comparison using serialization?

Thanks in advance!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 4 2008
Added on Mar 7 2008
5 comments
764 views