in Java 7 we have
o.hashCode();
Objects.hashCode(o);
Objects.hash(o);
The first 2 are roughly the same with the null point check, but
The default hashCode() of Object returns the memory address for the object. So if you have the following class:
class Car {
String make;
String model;
int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
}
then create two objects:
Car car1 = new Car("Toyota", "Corolla", 2010);
Car car2 = new Car("Toyota", "Corolla", 2010);
car1.hashCode() will be different from car2.hashCode() because each object will have a different memory address.
What if you want both car1 and car2 to return the same hash code? In this case, you should override the default Object hashCode() method for the Car class as follows:
@Override
public int hashCode() {
Object[] x = {model, make, Integer.valueOf(year)};
int hashArray = Arrays.hashCode(x);
return hashArray;
}
This will make car1.hashCode() equal to car2.hashCode() because the String.hashCode() calculates the hashCode based on the string contents, and the Integer.hashCode() will return the integer value itself.
In Java 7, you can just use Objects.hash(Object... values). So our new Car hashCode() will look as follows:
@Override
public int hashCode() {
return Objects.hash(model, make, year);
}
Objects.hash(Object... values) will call Arrays.hashCode for you.
Finally, Objects.hashCode(Object o) will do a null check. It will return 0 if the object is null. Else, it will call the objects hashCode() method.