Comparable interface provides compareTo method which is similar with Object’s equals method, except that it permits order comparisons in addition to simple equality comparisons, and it is generic. By implementing Comparable, a class indicates that its instances have a natural ordering. Sorting an array of objects that implement Comparable is as simple as this: Arrays.sort(a); […]
Methods Common to All Objects
Although Object is a concrete class, it is designed primarily for extension. All of its nonfinal methods (equals, hashCode, toString, clone and finalize) have explicit general contracts because they are designed to be overridden.
Override clone judiciously
The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately, it fails to service this purpose. Its primary flaw is that it lacks a clone method, and Object’s clone method is protected. You cannot, without resorting to reflection, invoke the clone method on a object merely because […]
Always override toString
While java.lang.Object provides an implementation of the toString method, the string that it returns i generally not what user of your class wants to see. It consists of the class name followed by an „at” sign (@) and the unsigned hexadecimal representation of the hash code, for example „PhoneNumber@163b91”. While it could be argued that […]
Always override hashCode when you override equals
A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violating of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet […]
Obey general contract when overriding equals
Overriding the equals method seems simple, but there are many ways to get it wrong, and consequences can be dire. The easiest way to avoid problems is not to override equals method, in which case each instance of the class is equal only to itself. This is the right to do if any of the […]