Thursday, April 16, 2015

Effective Java (Remarked) - Methods Common to All Objects

Item 8: Obey the general contract when overriding equals (performance, stability)

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 the equals method, in which case each instance of the class is equal only to itself. When you override the equals method, you must adhere to its general contract: Reflexive, Symmetric, Transitive and Consistent.

When use? especially in ORM classes.

Item 9: Always override hashCode when you override equals (performance, stability)

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 violation 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, and Hashtable.

When use? always you override equals.

Item 10: Always override toString (readability)

When practical, the toString method should return all of the interesting information contained in the object. One important decision you’ll have to make when implementing a toString method is whether to specify the format of the return value in the documentation.

When use? always you need to get class information human-friendly.

Item 11: Override clone judiciously (performance, stability, readability)

To recap, all classes that implement Cloneable should override clone with a public method whose return type is the class itself. This method should first call super.clone and then fix any fields that need to be fixed.

When use? to copy objects using specific attributes.

Item 12: Consider implementing Comparable (performance, stability, readability)

By implementing Comparable, a class indicates that its instances have a natural ordering. By implementing Comparable, you allow your class to interoperate with all of the many generic algorithms and collection implementations that depend on this interface.


When use? especially in ORM classes.

No comments: