Java Reference
In-Depth Information
// A hash code allows an object to be used in a hash table.
// Equal objects must have equal hash codes. Unequal objects are
// allowed to have equal hash codes as well, but we try to avoid that.
// We must override this method because we also override equals().
@Override public int hashCode () {
int result = 17 ; // This hash code algorithm from the topic
result = 37 * result + x ; // _Effective Java_, by Joshua Bloch
result = 37 * result + y ;
result = 37 * result + r ;
return result ;
// This method is defined by the Comparable interface. Compare
// this Circle to that Circle. Return a value < 0 if this < that
// Return 0 if this == that. Return a value > 0 if this > that.
// Circles are ordered top to bottom, left to right, and then by radius
public int compareTo ( Circle that ) {
// Smaller circles have bigger y
long result = ( long ) that . y - this . y ;
// If same compare l-to-r
if ( result == 0 ) result = ( long ) this . x - that . x ;
// If same compare radius
if ( result == 0 ) result = ( long ) this . r - that . r ;
// We have to use a long value for subtraction because the
// differences between a large positive and large negative
// value could overflow an int. But we can't return the long,
// so return its sign as an int.
return Long . signum ( result );
The purpose of the toString() method is to return a textual representation of an
object. The method is invoked automatically on objects during string concatenation
and by methods such as System.out.println() . Giving objects a textual represen‐
tation can be quite helpful for debugging or logging output, and a well-crafted
toString() method can even help with tasks such as report generation.
The version of toString() inherited from Object returns a string that includes the
name of the class of the object as well as a hexadecimal representation of the hash
Code() value of the object (discussed later in this chapter). This default implementa‐
tion provides basic type and identity information for an object but is not usually
very useful. The toString() method in Example 5-1 instead returns a human-
readable string that includes the value of each of the fields of the Circle class.
Search WWH ::

Custom Search