1. hashCode() must be overridden when equals() is overridden
2. when objects are equal then their hash codes should be as well
We begin with the the Car class that relies on default equality inherited from the Object class wherein the equals() method is simply a reference comparison.
package com.cars; public class Car { private int vin; //Vehicle ID Number public Car(int vin) { this.vin = vin; } public int getVin() { return vin; } }
package com.cars; public class TestingIdentity { public static void main(String[] args) { Car car1 = new Car(1); Car car2 = new Car(1); assert car1 != car2; // line 6 assert car1.equals(car2); // line 7 }
javac -sourcepath src -classpath ./build -d build src/com/cars/Car.java javac -sourcepath src -classpath ./build -d build src/com/cars/TestingIdentity.java java -ea -classpath ./build com.cars.TestingIdentity Exception in thread "main" java.lang.AssertionError at com.cars.TestingIdentity.main(TestingIdentity.java:7)
package com.cars; public class Car { private int vin; public Car(int vin) { this.vin = vin; } public int getVin() { return vin; } @Override public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (o.getClass() != this.getClass()) return false; Car car = (Car)o; if (car.getVin() == this.vin) return true; return false; } }
package com.cars; import java.util.Set; import java.util.HashSet; public class TestingIdentity { public static void main(String[] args) { Car car1 = new Car(1); Car car2 = new Car(1); assert car1 != car2; // line 8 assert car1.equals(car2); // line 9 Setset = new HashSet (); set.add(car1); set.add(car2); assert set.size() == 1; // line 14 } }
javac -sourcepath src -classpath ./build -d build src/com/cars/TestingIdentity.java java -ea -classpath ./build com.cars.TestingIdentity Exception in thread "main" java.lang.AssertionError at com.cars.TestingIdentity.main(TestingIdentity.java:14)
@Override public int hashCode() { return vin; }
The solution is a little simplistic but it does work for the given problem. A better solution is to use org.apache.commons.lang.builder.HashCodeBuilder.