Skip to content
Advertisement

When should I be overriding java.lang.Object methods?

Under what circumstances should I begin to consider overriding any of the following methods?

  • clone()
  • equals()
  • finalize()
  • hashCode()
  • toString()

Some of these have some obvious, somewhat specific answers, but I’m wondering more so about general conditions under which it would considered good practice to implement them.

Advertisement

Answer

clone()

Implement if you want an easy way to copy the object.

Many people discourage use of clone() and suggest using a copy-constructor instead. E.g. see Clone() vs Copy constructor- which is recommended in java.


equals()

Implement if you need to compare two instances for equality.

Required if object will be used as key in a HashMap (or similar), or inserted into a HashSet (or similar). Highly recommended of used in the TreeXxx variants, for compatibility with compareTo(), i.e. if class implements Comparable.


hashCode()

Implement if object will be used as key in a HashMap (or similar), or inserted into a HashSet (or similar).

Generally a good idea to always implement if you implement equals().


toString()

Generally implement to make debugging easier, especially if object will be inserted into a collection.

Implement if object has a simple textual representation, and you want to be able to output it without calling a method (e.g. getName() or getDescription()).


finalize()

Never. No code should rely on finalize() for resource clean-up, since there is no guarantee when, or even if, it will be called.

Resource-owning classes should implement AutoCloseable instead.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement