I have been overrided the hashcode and equals to find the value which have same startDate and closingDate. And I am getting the similar hash code for duplicate objects. When equating these objects I am getting boolean "false". In my understanding object==object compares the reference of the object, even though the reference are same; the code is returning false. Can you please help me to understand what is the issue. I have posted my code below:
Hashcode & equals Method
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.startDate == null) ? 0 : this.startDate.getDate());
result = prime * result + ((this.closingDate == null) ? 0 : this.closingDate.getDate());
return result;
}
public boolean equals(Object customer) {
if(customer == null || customer.getClass()!= this.getClass())
return false;
return this==customer;
}
Main.java
public class HashQuestion {
public static void main(String[]args) {
Map<Integer, Customer> custMap = new HashMap<Integer, Customer>();
custMap.put(1, createCustomer(1, new Date()));
custMap.put(2, createCustomer(2, new Date()));
custMap.put(3, createCustomer(3, new Date()));
Customer checkCustomer = createCustomer(1, new Date());
for (Customer cust : custMap.values()) {
if (cust.equals(checkCustomer)) {
System.out.println("Duplicate No: "+cust.getCustId()+ ", Start date: " +
cust.getStartDate().toString() + " End date: " +cust.getClosingDate().toString());
}
else
System.out.println("No: "+cust.getCustId()+ ", Start date: " +
cust.getStartDate().toString() + " End date: " +cust.getClosingDate().toString());
}
}
@SuppressWarnings("deprecation")
static Customer createCustomer(int number, Date date) {
Date closeDate = new Date();
Date startDate = new Date();
closeDate.setDate(date.getDate() + number);
startDate.setDate(date.getDate() - number);
return new Customer(number, number+1, startDate, closeDate);
}
}
Output:
No: 1, Start date: Wed Jun 20 19:42:46 IST 2018 End date: Fri Jun 22 19:42:46 IST 2018
No: 2, Start date: Tue Jun 19 19:42:46 IST 2018 End date: Sat Jun 23 19:42:46 IST 2018
No: 3, Start date: Mon Jun 18 19:42:46 IST 2018 End date: Sun Jun 24 19:42:46 IST 2018
checkCustomer object reference: Customer@643
Object references (which is in Map): [Customer@643, Customer@625, Customer@607]
Here object1 is having same reference as checkCustomer obj. However obj==checkCustomer, returns false.