O'Reilly logo

Java RMI by William Grosso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Accounting for Partial Failure

I said earlier that data objects are objects in which the behavior isn’t quite so important. There is one very important exception to this: a data object must implement equals( ) and hashCode( ), and these methods must be implemented based on the underlying values of the object’s data. The default methods, inherited from java.lang.Object are based on the location of the instances in memory.

In the case of Money, equals( ) is implemented directly, and hashcode( ) is inherited from ValueObject:

public abstract class ValueObject implements Serializable {
	private String _stringifiedRepresentation;
	private boolean _alreadyHashed;
	private int _hashCode;

	public ValueObject(String stringifiedRepresentation) {
		_stringifiedRepresentation = stringifiedRepresentation;
		_alreadyHashed = false;
	}

	public String toString(  ) {
		return _stringifiedRepresentation;
	}

	public int hashCode(  ) {
		if (false == _alreadyHashed) {
			_hashCode = _stringifiedRepresentation.hashCode(  );
			_alreadyHashed = true;
		}
		return _hashCode;
	 }
}

Tip

Unlike equals( ), with which you simply need to compare data fields, implementing hashCode( ) can be difficult—you have to come up with a good hashing algorithm for your objects. The way ValueObject does this is a fairly common trick—you generate a unique string for the values of your object and then use String’s hashing algorithm. It’s not foolproof, and it can be expensive if you don’t cache the hashcode, but it’s simple and works fairly well. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required