Q:

More on equals and hashCode

I understand the contract between the equals and hashCode methods. If equals is overridden, hashCode should also be. Can I override the hashCode method to always return the same value, say the int 23? Can I override the hashCode method to return a random number each time it is called?

A:

You shouldn't override hashCode to return a random value. It should always return the same value for the same instance.
This is clearly stated in the Javadoc :

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

You shouldn't return a constant value, since it would make a very poor hashCode when used in classes such as HashMap and HashSet.
This is also mentioned in the Javadoc :

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

