Comparable vs. Comparator in Java

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them? The following are two examples for answering this question. The simple examples compare two HDTV’s size. … Read more

How Java Compiler Generate Code for Overloaded and Overridden Methods?

Here is a simple Java example showing Polymorphism: overloading and overriding. Polymorphism means that functions assume different forms at different times. In case of compile time it is called function overloading. Overloading allows related methods to be accessed by use of a common name. It is sometimes called ad hoc polymorphism, as opposed to the … Read more

Java equals() and hashCode() Contract

The Java super class java.lang.Object defines two important methods: public boolean equals(Object obj) public int hashCode()public boolean equals(Object obj) public int hashCode() In this post, I will first show an example of a common mistake, and then explain how the equals() and hashCode() contract works. 1. A common mistake The common mistake is shown in … Read more