-Objects type variables can be compared by overriding equals() and hashcode()
methods (if we do not override equals() and hashcode() methods, the program will result into unexpected output)
-For objects to be equal, their equals() method should return true and hashcode() method should return same hashcode.
===========================================================
Example: To demonstrate how to compare primitive and reference data types. For reference data types such as Car in below example, the equals() and hashcode() methods are overridden so that "deep comparison" is possible.
import java.util.HashSet;
import java.util.Set;
public class TestCompare {
public static void main(String[] args) { int age = 20;// primitive
//compare with == for primitive data types
//check equality
if (age == 20) {
System.out.println("You are 20");
}
//Object type variable
Car a = new Car();
Car b = new Car();
a.setModel("Mazda");
a.setPrice(1000);
b.setModel("Mazda");
b.setPrice(1000);
if(a.equals(b)) {
System.out.println("Equal Car");
} else {
System.out.println("Not equal Car");
}
//adding two objects a and b with same states
//to Set will results into one unique object
//only. Set calls Objects' equals() and hashcode()
//methods to compare their contents
Set<Car> carSet = new HashSet<Car>();
carSet.add(a);
carSet.add(b);
System.out.println("Car Set size:" + carSet.size());
}
}
Output:
You are 20
Equal Car
Car Set size : 1
--------------------------------------------------
public class Car {
private String model;
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
//method to compare state of this and other object //which is passed as a parameter
//if all states are same between two objects then
//this method will result true, else false
@Override
public boolean equals(Object b) {
boolean result = false;
if (b instanceof Car) {
Car c = (Car) b;
result = c.getModel().equalsIgnoreCase(getModel()) &&
c.getPrice() == getPrice();
}
return result;
}
//Require to override when overriding equals() method //so that two equals objects will return same hashcode
//which will avoid duplicate elements in Hash
//like collections, such as HashSet
@Override
public int hashCode() {
return (int)(price/10000)*7;
}
}